The Device Code authentication flow is designed for input-constrained devices and applications where a user cannot easily enter credentials directly. It allows users to authenticate using a separate web browser or device.
The Device Code flow operates as follows:
This endpoint initiates the device code authentication process.
POST /oauth2/v2.0/devicecode
| Name | Description | Required |
|---|---|---|
| client_id | The client ID of your application. | Yes |
| scope | The scopes your application requires (e.g., https://graph.microsoft.com/.default). |
Yes |
| tenant | (Optional) The Azure AD tenant ID or domain. Defaults to common. | No |
{
"device_code": "aGVsbG8gdGhlcmU=",
"user_code": "ABCD-EFGH",
"verification_url": "https://microsoft.com/devicelogin",
"expires_in": 1800,
"interval": 5,
"message": "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD-EFGH to authenticate."
}
Key Fields:
device_code: A secret code used by the client to poll for an access token.user_code: The code displayed to the user for entry on the verification URL.verification_url: The URL the user needs to visit to authenticate.expires_in: The lifetime in seconds of the device_code.interval: The minimum number of seconds the client should wait between polling for an access token.After initiating the flow, your application should poll this endpoint to check if the user has completed the authentication on the verification URL.
POST /oauth2/v2.0/token
| Name | Description | Required |
|---|---|---|
| grant_type | Must be set to urn:ietf:params:oauth:grant-type:device_code. |
Yes |
| client_id | The client ID of your application. | Yes |
| device_code | The device_code obtained from the initial device code request. |
Yes |
{
"token_type": "Bearer",
"scope": "https://graph.microsoft.com/.default",
"expires_in": 3600,
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"refresh_token": "rT5N...tU"
}
{
"error": "authorization_pending"
}
{
"error": "expired_token"
}
The client should continue polling until it receives an access token or an error indicating the code has expired or been cancelled.
authorization_pending response by waiting the specified interval before polling again.expires_in value for the device code and inform the user if they take too long.access_token and refresh_token.device_code and subsequent token requests securely. Do not expose sensitive information in client-side code.
Python (using a hypothetical library)
from azure_identity import DeviceCodeCredential
import asyncio
async def main():
credential = DeviceCodeCredential()
token = await credential.get_token("https://graph.microsoft.com/.default")
print(f"Access Token: {token.token}")
if __name__ == "__main__":
asyncio.run(main())