# OAuth2.0 Authorization Code flow
source: https://developer.mastercard.com/cross-border-services/documentation/ref-app/oauth2-access-token-based-authentication-details/index.md

As defined in [OAuth2.0 RFC 6749, section 4.1](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1), Authorization Code Grant Type flow of OAuth2.0 involves two parts:   

1. The **Authorization flow** that runs in the browser where the client redirects to the OAuth server and the OAuth server redirects back on completion. This step provides the authorization code that is required to obtain the token.   
2. The **Token flow** which is a backend call from the client to the token endpoint of the OAuth server used to obtain the token using the authorization code obtained earlier.   

The following diagram represents the flow to obtain a token to make a successful Cross-Border Services Balance API call.

![crossborder-api-call-diagram](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/author_code.png)

* **Authorization code** -- Short lived code having 15 minutes validity used in the Token API service for getting an access token and refresh token.
* **Access token** - Short lived token having 15 minutes validity used in the authorization header for consuming Balance API service.
* **Refresh token** - Long lived token having 90 days validity used to regenerate the access token during 90 days validity. After expiry, the customer connects to the web browser portal for getting a new authorization code that will allow creating new access and refresh token credentials.   

Now let's look into the step by step detail on each of the flows.

## Part 1: Authorization Flow {#part-1-authorization-flow}

**Pre-requisite:**

You must be onboarded on the [Mastercard Connect Portal](https://mastercardconnect.com) before proceeding with the below steps.

**Step 1:** Login to the OAuth Web application at the below provided urls and provide your credentials. See the screenshot below.

*OAuth Web application URLs:*

* Sandbox/MTF URL: [https://sandbox.consent.xbs.mastercard.com/xbsconsent/launchconsent?redirect_url={client_redirect_url}\&client_id={client_id}\&partner_id={partner_id}](https://sandbox.consent.xbs.mastercard.com/xbsconsent/launchconsent?redirect_url=%7Bclient_redirect_url%7D&client_id=%7Bclient_id%7D&partner_id=%7Bpartner_id%7D)
* Production URL: [https://consent.xbs.mastercard.com/xbsconsent/launchconsent?redirect_url={client_redirect_url}\&client_id={client_id}\&partner_id={partner_id}](https://consent.xbs.mastercard.com/xbsconsent/launchconsent?redirect_url=%7Bclient_redirect_url%7D&client_id=%7Bclient_id%7D&partner_id=%7Bpartner_id%7D)

***client_redirect_url*** : This must be provided by you where you want the call to be redirected to, after successful login.  

***client_id*** : This must be provided by you. This is obtained by creating a [Mastercard Developers account](https://developer.mastercard.com/account/sign-up) and then create a project choosing the **Mastercard Cross-Border Services** API service. The project will generate the client id/ consumer Key and the project keys required to use the APIs in each of the environments.  

The [Quick Start Guide](https://developer.mastercard.com/cross-border-services/documentation/tutorials/guide-create-project/index.md) provides detailed information about creating a project and downloading the project keys.

![mc-conect-login-page](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/consent_app_login.png)

**Step 2:** After successful login, you will be redirected to the url provided by you in the OAuth Web application URL as described in step 1 above, and you will be provided with the authorization code (i.e. code) appended in the URL. For Example :

![url-with-authorization-code](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/consent_app_auth_code.png)

You may use this authorization code from to request for the token as described in the Part 2.
Note: The validity of authorization code is 15 minutes. You must continue with next steps to get the access token before the authorization code expires.

Also, for your convenience, here are some of the common error scenarios (with reasons) that you might encounter in above steps.  

### Common Error Codes {#common-error-codes}

|                     Scenario                     |                                                                                  Error                                                                                   |
|--------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ClientId not found in request parameter          | ![ClientId-not-found-error](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/client_Id_not_found_concentError.png)             |
| RedirectUrl field not found in request parameter | ![RedirectUrl-field-not-found-error](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/redirect_url_not_found_concentError.png) |
| Generic error                                    | ![generic-error](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/generic_concentError.png)                                    |

## Part 2: Token Flow {#part-2-token-flow}

### Option 1: Generate Access token/ Refresh token using a valid authorization code {#option-1-generate-access-token-refresh-token-using-a-valid-authorization-code}

Make a call to the token generation endpoint by passing the valid authorization code obtained in the above steps.

* Request URI:

  * Sandbox/MTF URL: <https://sandbox.api.mastercard.com/global/saat-auth/oauth2/token>

  * Production URL: <https://api.mastercard.com/global/saat-auth/oauth2/token>

<!-- -->

* Content type: application/x-www-form-urlencoded

* Sample_Request_Body

```Sample_Request_Body
grant_type=authorization_code
&code=<as received by consent application>
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion=<client_assertion_token_goes_here>
&code_verifier=<client ID>
&redirect_uri=https://redirect.me/here
 
```

Tip:   

* Ensure the authorization code and client assertion are valid and not expired.

* Please see useful tips section below for steps to generate client assertion.

* Sample_Response

```Sample_Response
{
    "access_token": "TlBN45jURg",
    "token_type": "bearer",
    "expires_in": <access token lifetime>,
    "scope": "com.mastercard.send.xb.services:send-api-crossborder:PSP_PI_RO offline_access",
    "id_token": null,
    "refresh_token": "9yNOxJtZa5",
    "refresh_token_expires_in": <refresh token lifetime>
}
 
```

### Option 2: Re-generate Access token using a valid Refresh token (without requiring an authorization code) {#option-2-re-generate-access-token-using-a-valid-refresh-token-without-requiring-an-authorization-code}

* Request URI:

  * Sandbox/MTF URL: <https://sandbox.api.mastercard.com/global/saat-auth/oauth2/token>

  * Production URL: <https://api.mastercard.com/saat-auth/oauth2/token>

<!-- -->

* Content type: application/x-www-form-urlencoded

* Sample_Request_Body

```Sample_Request_Body
grant_type=refresh_token
&client_id=<clientId> // public clients to present client_id here.
&refresh_token=<previously issued refresh token>
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer // non public clients to present the client assertion type and assertion token.
&client_assertion=<client_assertion_token_goes_here>
 
```

Note:   

* Ensure the authorization code and client assertion are valid and not expired.  
* Please see below for steps to generate client assertion.  
* Sample_Response

```Sample_Response
{
   "access_token": "TlBN45jURg",
   "token_type": "Bearer",
   "refresh_token": "9yNOxJtZa5",
   "expires_in": <access token lifetime>
   "refresh_token_expires_in": <refresh token lifetime>
}
 
```

Note: Once you have successfully obtained the access token, pass the token in the authorization header of the Mastercard Cross-Border Services API request.

You may look at the [API Tutorial for the Authorization Code based OAuth2.0](https://developer.mastercard.com/cross-border-services/documentation/tutorials/oauth2-api-sdk-tutorial-access-token/index.md) or [the Reference Tutorial for Authorization Code based OAuth2.0](https://developer.mastercard.com/cross-border-services/documentation/ref-app/oauth2-reference-app-tutorial-access-token/index.md), if you need help on connecting to the Mastercard Cross-Border Services API using access token.

### Useful Tips: {#useful-tips}

#### How to generate the client assertion required for the above API calls {#how-to-generate-the-client-assertion-required-for-the-above-api-calls}

a) Checkout the maven project of Token Generation Utility from : <https://github.com/Mastercard/send-util-crossborder-oauth2>.

b) Open maven view in IDE and run maven clean and install. This will add dependencies to your project.

![maven-example](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/token_generation_utility.png)

c) Set the values for the following:
* Oauth

```Oauth
consumerKey=YourConsumerKey

keyAlias=YourKeyAlias

keyStorePassword=YourKeystorePassword

p12File=yourKeyFile
```

![select-values-in-maven](https://static.developer.mastercard.com/content/cross-border-services/documentation/images/token_generation_utility_run.png)

d) Run Oauth2RequestTokenGeneratorTest.java class

e) This utility will give you Request Token (i.e. \<client_assertion_token\> used in the Access Token API call) which will be used to generate Access Token.
