Search code examples
apioauth-2.0microsoft-graph-apidynamics-365

OAuth v2 Authorization Code returned in Location HTTP header


I am using the OAuth to obtain an access token from Microsoft Graph. I am specifically using the Authorization Code grant type. The first step is to request a Code via an HTTP GET. The code is then used in a second HTTP POST API call along with the client_id and client_secret.

What is confusing me is how the Authorization Code is being delivered. It is returned as part of the HTTP Headers named Location.

HTTP Response Header

Is this expected? I was looking for it in a response body similar to how an access_token is returned. Is returning the Code via the Location header expected?


Solution

  • AUTHORIZATION CODE FLOW

    This flow is very standard for browser clients, so behaviour looks correct:

    • The browser receives the authorization code as part of a redirect, where there are security risks, such as the code being included in logs or visible to the user, or possibly being intercepted by a malicious party.
    • The UI's logic then makes a direct HTTPS call to swap the code for tokens. Using two stages to get OAuth tokens reduces the threat surface for browser clients.

    TESTING THE CODE FLOW

    The Code Flow is tricky to test in tools like Postman. Have a look at OAuth Tools as a better alternative - see also this video.

    Here are some values of mine you can use as a first step:

    • Select Add Environment and enter the base Azure AD URL, which for my developer account has this value as issuer, then click discover to populate other endpoints:
      https://login.microsoftonline.com/7f071fbc-8bf2-4e61-bb48-dabd8e2f5b5a/v2.0
    • Then start a Code Flow with a client id such as this one of mine: c5ea6d78-c637-4f7f-b238-2264f5d4b479
    • Then, once the settings look like the below screenshot, start a login redirect:

    Code Flow Settings

    You can then update to your own settings and do the same thing with a test user. Then scroll down and select the 'Redeem Code' option, and use the client_secret_post option to swap the code for tokens. Then view the JWT details etc.

    One problem is that my Azure AD client is a Single Page App and Azure AD requires this header to be added to the curl request during the redeem step. Not sure if you will face that problem and I will see if I can get the tool updated to allow extra headers etc to be typed in.

    • -H 'Origin: https://web.mycompany.com'