Search code examples
javaazureazure-active-directoryazure-api-managementazure-api-apps

how to get 'code' for getting access_token when using Azure AD Graph API


I am newbie to Azure AD and want to interact with it through my java app. After doing some research, I found that we need to get bearer_token in order to use Graph API for Azure AD.

I am following this link to get bearer token but facing issue with one of parameters.

Now as shown in below image from above link, there are several parameters and information related to them is given like what they are and how to retrieve them but I dont see any information related 'code' parameter.

enter image description here

Can somebody tell me what is this 'code' and how am I supposed to get it?

Note: I have free trial account of Azure AD.

Any help is much appreciated!

Regards, Amit


Solution

  • You are trying to use Authorization Code Grant Flow. You can read in detail about the flow and steps here in Microsoft Docs

    It's a two step process:

    STEP 1: Get Authorization Code by hitting the /authorize endpoint. You will get an authorization_code back as response for this call. Example shown below:

    // Line breaks for legibility only
    
    https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
    client_id=6731de76-14a6-49ae-97bc-6eba6914391e
    &response_type=code
    &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
    &response_mode=query
    &scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
    &state=12345
    

    STEP 2: Once you have an authorization_code from previous call, you can redeem it for an access token. Example shown below:

    // Line breaks for legibility only
    
    POST /{tenant}/oauth2/v2.0/token HTTP/1.1
    Host: https://login.microsoftonline.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=6731de76-14a6-49ae-97bc-6eba6914391e
    &scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
    &code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
    &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
    &grant_type=authorization_code
    &client_secret=JqQX2PNo9bpM0uEihUPzyrh    // NOTE: Only required for web apps