Search code examples
oauth-2.0

oAuth2.0: Why need "authorization-code" and only then the token?


Using oAuth 2.0, in "authorization-code" Authorization Grant, I first call to "/authorize", get the code, and then use this code within a call to "/token" to get the access-token.

My question: why this is the flow? I guess it is from a security reason, but I cannot figure it out. Why the implementation is this way, and not getting the access-token immediately after the first call ("/authorize")?

Why do we need this code for?


Solution

  • The authorization code flow is meant for scenarios where 3 parties are involved.

    These parties are:

    • Client

      The user with his web browser. He wants to use your application.

    • Provider

      Has information about the user. If somebody wants to access this data, the user has to agree first.

    • Your (web) application

      Wants to access information about the user from the provider.

    Now your app says to the user (redirecting his browser to the /authorize endpoint):

    Hey user, here is my client id. Please talk to the provider and grant him to talk to me directly.

    So the user talks to the provider (requests the authorization code and returns it to your app by opening your callback URL in his browser):

    Hey provider, I want to use this app, so they require to access my data. Give me some code and I give this code to the application.

    Now your app has the authorization code which is already known by client AND the provider. By handing this over to the provider your app can now prove, that it was allowed by the client to access his data. The provider now issues your (web) app an access token, so your (web) app won't have to redo these steps each time (at least for a while).

    In case of other application types where your app is running directly at the client side (such as iPhone/Android apps or Javascript clients), the intermediate step is redundant.