OAuth 2.0 : How an application use OAuth to access another application API(under consent and permission boundary) - Authorization end point and Token end point ; Calling a protected API from a Web App using OAuth

OAuth2.0  (Open Authorization) is an open standard and commonly technique to grant websites or applications access to user's information/credentials on other websites without giving them the passwords.

From RFC 6749 https://tools.ietf.org/html/rfc6749

The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

In the OAuth world, a client application wants to gain access to a protected resource on behalf of a resource owner (usually an end user)

In this post first first we will see challenges which forced industry to come together and invested a standard way of accessing first party/third party application using password-less approach. 

Imagine a scenario - a user is already signed in LinkedIn and let's say LinkedIn wants to suggest you to invite all of your Google contacts to become part of your LinkedIn network.
In order to achieve this LinkedIn would start workflow with asking Gmail/Google contacts username and password and complete accessing contacts in 4 steps highlighted below.

Let's understand problem with above approach which sets playground for OAuth.  

  1. The first problem is that granting access of credentials to an entity that is not the custodian of those credentials is always a bad idea. 
  2. Although LinkedIn has right intention to fetch contacts but  LinkedIn can actually use this username and password to do whatever they want with my Gmail, Blogger, etc as credentials are same. Password Sharing is called as Anti-Pattern and it forced industry to find a common ground which is secure and provide app-2-app access for better flexibility.

In order to resolve challenges outlined above the industry came up with a specification which highlights

  • How an application can delegate authorization in restricted manner - Gives the application a way to make API requests 
  • Opens door for accessing its API/secured resources from a known entity - register yourself before accessing another application.  

OAuth 2.0 introduces a new entity called authorization server which handles operations related to delegated authorization. An authorization server has two endpoints - 

  1. Authorization endpoint: Its designed to deal with end-user. It allows the user to express interest/intent whether they want a certain service/application(first party or third party) to access their resources in a certain fashion.

  2. Token endpoint: It is designed to deal with software to software communication and takes care of actually executing on the intent that the user expressed in terms of permission and consent.

Let's revisit accessing Google contacts from LinkedIn application(this time I am using LinkedIn web to initiates contacts access). 

I am logged-in to my LinkedIn account and followed above steps 1 to 5. If click on "Allow" 
  • I am expressing my interest to access Google Contacts & download the same by LinkedIn (as highlighted by LinkedIn to "See and download contact info automatically saved in your 'Other contacts'") 
Lets understand what is happening in background - LinkedIn redirect user to Google authorization server(AS), AS sends back Authorization code & finally LinkedIn establish software to software communication to fetch contact details. 
 
  1.  LinkedIn prepares an authorization request and redirect the user’s browser to Gmail’s authorization server and, in particular, the authorization endpoint. Http status code 302 indicates resources moved temporarily(in this case to Gmail authorization endpoint).

    Note: LinkedIn register itself as a known application with authorization server(AS) and AS provides client-Id and client-secret. For any software to software communication LinkedIn uses this combination to prove its Identity(while accessing token end point of AS).

  2.  The authorization endpoint is used by Gmail to prompt the user to provide Gmail login credentials (Credentials passing to Gmail endpoints is safe). Gmail authorization server prompt user saying something along the lines of, "A known client LinkedIn needs to access Gmail own APIs using your privileges. In particular, they want to see your contacts. Are you okay with it?"  if User clicks Allow{Screen# 5 in LinkedIn login workflow image}, user provides consent for the same.

  3. Once the user submits form by clicking Allow button, the authorization server emits an authorization code.
    An authorization code is an opaque string that constitutes a reminder for the authorization server of the fact that the user did grant consent for those permissions for "a particular client" client.

  4. The authorization code is returned to LinkedIn via browser, after this stage all commutation is Software to Software (between LinkedIn and Gmail) on the basis of Authorization code(AC) which has been facilitated by AS via User to LinkedIn (Here AC is tri-party agreement entity).

  5.  LinkedIn will reach out to the token endpoint of the authorization server and present its own credentials (client id and client secret) and the authorization code and substantially saying, "Hey, this user consented for this and I'm LinkedIn. Can I please get access to the resource I want?"

  6. Authorization server validates combination of client-Id and client-secret for application's identity and authorization code generated in step-2(Authorization server keeps track of authorization code generated with permission scope), finally the authorization server will emit a new kind of token called Access token.

  7. The access token is an artifact that provides an ability to access the Gmail APIs on the user’s behalf within consented scope. 

  8.  On successful API access, LinkedIn provides list of contacts with whom I can connect and send email.


Scope is the keyword to represent the permissions a client requested on behalf of the user. This mechanism effectively solved the problem of excessive permissions, providing a way to express and enforce delegated authorization. This is known as canonical OAuth2 use case.


Calling an API from a Web App

Let's assume we have a resource service provider which give availability of a certain resource(Auth protected). A user execute availability service through an app running in localhost and user is already signed-in with application. 

We will run commands to visualize how authorization code and access token are generated. And finally application uses access token to lookup for resource availability on user's behalf.

Note: Authorization code grant is a delegated flow. It allows clients to do things on the user’s behalf, which means that the user’s capabilities are a hard limit for what an application can do on the user’s behalf .

 
A prerequisite to run commands to generate AC(authentication code ) and AT(access token) is to setup  an Authorization server(AS) for "service.provider". Follow Setup okta auth server and custom scope to setup Authorization server and ready with authorization server client-id, client-secrets.

Follow below steps from 1 to 8 which summarizes interactions among client, application and authentication server with commands involved. Run below commands with assumption client is already signed-In to application.


  1. Route Request: The user hits a route of the web application that allows the user to find resource availability. For getting resource availability,it require accessing the availability API on behalf of the user; hence, accessing that route causes the web app to generate a request for delegated access

  2. Authorization Request: Application prepares a redirection request(302 HTTP status code) for authorization server. Request template message looks like this:
        https://dev-xxxxxx.okta.com/oauth2/default/v1/authorize?
        response_type=code&
        scope={YOUR_SCOPE}&
        client_id={YOUR_CLIENT_ID}&
        state={RANDOM_STRING}&
        redirect_uri=https://example-app.com/redirect&
        code_challenge={YOUR_CODE_CHALLENGE}&
        code_challenge_method=S256
    

     
    YOUR_SCOPE
    Custom scope created while setting up Okta for app. 
    
    YOUR_CLIENT_ID
    Post application creation we get clientId
    
    RANDOM_STRING
    Create the PKCE Code Verifier: Generate a random string between 43-128 characters long 
    using https://example-app.com/pkce YOUR_CODE_CHALLENGE Base64-URL-encoded SHA256 hash of the random string generated above.
  3. Execute redirection end point:  Run following command in browser(simulate hitting authorization end point).
        https://dev-71227370.okta.com/oauth2/default/v1/authorize?
        response_type=code&
        scope=availability&
        client_id=0oa49rv6d5DV3MMfC5d7&
        state=8142744000&
        redirect_uri=http://localhost:8080/authorization-code/callback&
        code_challenge=HrtVSEgox1Loi_TIz6SMgT8FBjd1-dxuGx48WUqiViE&
        code_challenge_method=S256

    Note: I am already signed-in in Okta account from same browser, that's why Okta Auth server does not enforce for entering login credentials. If you excute above command in incognito window - you will prompt to sign-in.

  4. In Browser URL we can have response with code as

  5.  Get access token from code: If you got back an authorization code, you’re ready to exchange that for an access token.
    Make a POST request to the token endpoint to exchange temporary authorization code for an access token. Generic curl command template:
        curl -X POST {TOKEN-END-POINT} \
        -d grant_type=authorization_code \
        -d redirect_uri=https://example-app.com/redirect \
        -d client_id={YOUR_CLIENT_ID} \
        -d client_secret={YOUR_CLIENT_SECRET} \
        -d code_verifier={YOUR_CODE_VERIFIER} \
        -d code={YOUR_AUTHORIZATION_CODE}
    

  6. Execute curl command with token end point, client-Id and secret.
        n0r0082@m-c02z31rnlvdt ~ % curl -X POST https://dev-71227370.okta.com/oauth2/default/v1/token \
        -d grant_type=authorization_code \
        -d redirect_uri=http://localhost:8080/authorization-code/callback \
        -d client_id=0oa49rv6d5DV3MMfC5d7 \
        -d client_secret=gd7q2khudlkSht9B8XAhh0nYEmySL_XNZDePDt9K \
        -d code_verifier=56c0605645a56b561f3239ddd7f00525983a0f40c3e1c3efbec29717 \
        -d code=DyClTt8uVsjXgX-CTix-agg0B2BRbxcBaNHve8H1IQM
    {"error":"invalid_grant","error_description":"The authorization code is invalid or has expired."}%
    

    Since authorization token are short lived value, if we delay in POST call exceution - code will expire. Re-run step-4 with SHA-256 string and get new code and keep a note of code_verifier.

  7. If every validation at token end point passed , we’ll get a response that includes an access token (Token end point respond with Access token to application).
 
 --------========-------------
 

3 Comments

  1. The website analysis will report on all of the on page elements to make sure that everything that should be on the site, is there, and that these elements are sufficiently optimized. This includes mainly menu, image and link data, such as titles and alt tags. signup com

    ReplyDelete
  2. pg slot แนะนำเกมสล็อต ที่ควรเล่นทำเงิน เสริมความปัง พร้อมรับตังรัว ๆ ไปกับเกม สล็อตออนไลน์ เกมเล่นง่าย ทำกำไรได้ไม่ยั้ง ใน pg slot เว็บตรงสล็อตที่ดีที่สุดในตอนนี้เลยทีเดียว

    ReplyDelete
  3. Fantastic breakdown of OAuth authorization codes and access tokens! The visualizations and explanations really help clarify a complex topic. I especially appreciated the step-by-step walkthrough of the authorization flow. This post is a great resource for anyone working with OAuth. Thanks for the detailed and informative content!

    ReplyDelete
Previous Post Next Post