# OAuth 2.0 authentication \[GitHub example\]

**URL:** https://community.linx.software/community/t/oauth-2-0-authentication-github-example/487
**Category:** Guide
**Created:** [December 2, 2020, 9:01am UTC](https://community.linx.software/community/t/oauth-2-0-authentication-github-example/487 "2020-12-02T09:01:10Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![ronan](https://community.linx.software/community/user_avatar/community.linx.software/ronan/32/433_2.png) [@ronan](https://community.linx.software/community/u/ronan)
#### Post date: [December 2, 2020, 9:01am UTC](https://community.linx.software/community/t/oauth-2-0-authentication-github-example/487/1 "2020-12-02T09:01:10Z")

</div>

## Introduction

The [OAuth 2.0 Authorization Framework](https://tools.ietf.org/html/rfc6749) enables third-party applications such as a Linx Solution to obtain access to protected resources (i.e account details, documents etc) from a host (i.e. [Microsoft](https://docs.microsoft.com/en-us/graph/auth/?context=graph%2Fapi%2F1.0&view=graph-rest-1.0), [Facebook](https://developers.facebook.com/docs/graph-api), [GitHub](https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#authentication) etc. ) with permission from a `resource owner` (user). This is achieved by orchestrating an approval interaction between the resource owner, the host and the third-party application.

The authorization action by the resource owner (user) typically happens only once and following that there is a cycle of client-to-server re-authorization that ‘refresh’ the application’s authentication credentials.

The advantage of using the OAuth 2.0 flow is that a resource owner’s personal credentials (i.e. password and username) are never shared and the resource owner does not have to pre-configure anything on their side, only action the authorization when requested.

In order to implement the OAuth 2.0 - [Authorization Code Grant](https://tools.ietf.org/html/rfc6749#section-4.1) flow in Linx, a combination of hosting and consuming REST web services will be used. This will allow resources owners to authorize your application to access their resources without any manual intervention.

The below sections are covered in this guide:

- [Authorization Code Grant flow overview](#authorization-code-grant-flow)
- [Building a basic generic authenticator with Linx](#building-generic-authenticator)
  - [Registering your application](#registering-your-application)
  - [Authorization Request](#authorization-request)
  - [Exchange Authorization Code for an Access Token](#exchange-code-for-token)
  - [Returning the access token](#return-access-token)
  - [Making a request with the access token](#make-request-using-token)

- [Automating the whole flow](#automating-whole-flow)
  - [Automatically re-direct users to the Authorization URI](#redirect-users-to-auth-uri)
  - [Automatically request tokens after authorization](#automatically-generate-token)
  - [Customizing the response](#customizing-response)

- [Storing and retrieving the access token](#storing-and-retrieving-access-tokens)  
  

 **Need help?**  
  
 For personal support queries, please contact **support@linx.software** or reply on this article.
  

Please note the terms 'Process' and 'Custom Type' have been depreciated and have been replaced with 'Function' and 'Type' respectively. More details [**here**](https://linx.software/docs/releasenotes/linx/5.20.2.0/).

## Authorization Code Grant flow

The below diagram illustrates the OAuth 2.0 - Authorization Code Grant:

 ![image](https://community.linx.software/community/uploads/default/original/1X/f14abddb42073c4da4337be390735a14ca22f604.png)

  

- **(A)**: The flow is initiated by the resource owner (user) triggering the flow from the user-agent (browser) - this is done by the user browsing to a URL which will execute a request against a Linx API (client).

- **(B)**: The resource owner then authorizes (or denies) the client’s access request via the user-agent (broswer).

- **(C)**: The authorization server redirects the user-agent back to the client using the  
redirection URI provided earlier (in the request or during client registration).

- **(D)**: The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification.

- **(E)**: The authorization server authenticates the client, validates the authorization code, and ensures that the redirection URI received matches the URI used to redirect the client in step (C). If valid, the authorization server responds back with an access token and, optionally, a refresh token.

## Building a basic generic authenticator with Linx

In the following sections we will be covering how to build an automated authenticator that will allow you to connect to any API via OAuth 2.0.

The resulting user flow will look like the below:

![Generic OAuth 2 Provider - Automated Flow - Complete](https://community.linx.software/community/uploads/default/original/1X/5a5030ddce653376eca3dcb771fd700293cc8cbe.gif)

 **The explanations below are mostly for Linx5 users. We`ve included a sample built in Linx version 6**   
  
 Feel free to contact support@linx.software and we'll assist. 

 **Sample:**  
  
 A sample Solution has been provided below to aid understanding and provide a "basic" template for implementing the OAuth 2.0 flow in Linx.

> Linx5 [GenericOAuth2Authenticator.lsoz](https://community.linx.software/community/uploads/short-url/zwhCnAoluddQv0NXj8ISkuSikZ8.lsoz) (26.3 KB)  
> Linx6.0.5 [GenericOAuth2Authenticator.zip](https://community.linx.software/community/uploads/short-url/yZHORn1au6ObqlQXbGN7ggvvByY.zip) (47.4 KB)

### Registering your application

In this tutorial, I will be using the example of connecting to [GitHub](https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api).

Before connecting to your target API, you need to gather the below details:

- **Client credentials:** The Client ID and Client Secret (sometimes referred to as App ID/App Secret). These are obtained by registering an application on the provider’s website or developer portal.
- **Endpoint URIs:** The Authorization and Token generation URIs should be available on the official documentation of the platform you are trying to connect to.
- **Redirection URI:** The redirect URI or **Callback UR** L is used to return the Access Token. This is set when registering the application and can be changed at a later stage.

In order to generate the above information, you need to [register your App](https://github.com/settings/developers) on the providers website/developer portal.

 **Note:**  
  
 For GitHub, ensure you register an "OAuth application".

After you have registered your application, you should have:

- Client ID
- Client Secret
- Redirect URI

Example of registering a new application (GitHub):

 ![image](https://community.linx.software/community/uploads/default/original/1X/429fff0b0a79a765b20aa34f85b348d3f17ced59.png)

Application’s (client) identifiers (GitHub):

 ![image](https://community.linx.software/community/uploads/default/original/1X/81acda1a3afd77ada08f0baaf7f918fa0da622a7.png)

**Important** : Ensure you generate a `client` secret and store it somewhere for later:  
 ![image](https://community.linx.software/community/uploads/default/original/1X/29a3186fcb1c56b1615be081333c716202301c6d.png)

### Authorization Request

#### Overview

The [Authorization Request](https://tools.ietf.org/html/rfc6749#section-4.1.1) involves the `client` (Linx) constructing a URI which points to the target host authorization endpoint. The `resource owner` (user) is directed to this URI following by the `user-agent` (web browser) , following this, he/she will authorize the application to have access to the `protected resource` (typically indicated by the `scope` parameter).

The **Authorization URI** is in the following format:

```auto
{host}{authorize-path}?response_type={response-type}&client_id={client-id}&scope={scope}&state={state}&redirect_uri={redirect-uri}

```

| Name | | Description | Example |
| --- | --- | --- | --- |
| `{host}` | REQUIRED | Host server | `https://github.com` |
| `{authorize-endpoint}` | REQUIRED | Authorization endpoint for Host server | `/login/oauth/authorize` |
| `{response_type}` | REQUIRED | Value must be set to `code` | `code` |
| `{client_id}` | REQUIRED | Client identifier generated on target system application registration | `8527f38c3c4a0d8726fa` |
| `{scope}` | OPTIONAL | Optional list of access scopes , depending on the host | `repo, user ` |
| `{state}` | RECOMMENDED | Random string of characters used to verify the response from the server and prevent cross-site forgery | `QjKc` |
| `{redirect_uri}` | OPTIONAL | Redirect URI where the server will send a request to containing the `authorization code` after a successful authorization | `http://localhost:8080/oauth/token` |

The built up URI will be similar to the below:

```http
https://github.com/login/oauth/authorize?response_type=code&client_id=xxxxxxxx&scope=repo, user&state=QjKc&redirect_uri=http://localhost:8080/oauth/token

```

 **Tip:**  
  
 Try it yourself by manually creating the `Authorization URI` with your client credentials.

The Authorization URI will need to be browsed to every time you want to re-initiate the token generation flow. You can save this URI somewhere for quick reference, however, during development you’ll most likely need to remove and re-add apps, and therefore generate new client identifiers. In order to make life easier in such cases we are going to get Linx to build up the `Authorization URI` for us.

This will be a ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) that takes in a number of client credentials that we generated in the previous step.

The ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) will return a single output which will contain that input values, built up using string manipulations. This way, whenever the client identifiers change, we can update a single value in our Linx Solution and regenerate the Authorization URI.

To create a generic ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) that will generate and return the `Authorization URI`:

1. Create a new **Solution**.

2. Add a **Process** and rename it to `GenerateAuthorizationUri`.

3. Configure the **GenerateAuthorizationUri** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) to have the below **$.Input** values:

4. Configure the **GenerateAuthorizationUri** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) to have a single **$.Result** with the Name of `uri`.

5. Add a [SetValueFNC](https://linx.software/docs/reference/plugins/linx/content/setvalue) to the process.

6. For the Target, reference `$.Result.uri`.

7. For the Source, use an expression to build up the query values of the uri along with the input client credentials:

8. Debug the **GenerateAuthorizationUri** process.

9. When the ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) completes, take a look at the Debug Values panel and take note of the `$.Result.uri` value.

10. Copy the `uri` and paste it in your web browser.

11. You should be promoted to authorize your application:  

12. Once you’ve granted access, your `user-agent` (browser) should redirect you to the `Redirect URI` that you set earlier, i.e. `http://localhost:8080/oauth/token`.

13. The URL will contain 2 query parameters:

For the next section we will be using the value of the `code` parameter. The `state` parameter will be touched on later.

### Exchange Authorization Code for an Access Token

#### Overview

After the [Authorization Response](https://tools.ietf.org/html/rfc6749#section-4.1.2) has been recieved, the `code` parameter can be [exchanged](https://tools.ietf.org/html/rfc6749#section-4.1.3) with the host for an `access token`.

This typically involves making a `POST` request to the token issuing endpoint , with a `Content-Type` of `URL encoded` , submitting the identifiers below as the list of `URL encoded content` parameters.

```auto
    POST https://github.com/login/oauth/access_token?
       client_id={client-id}
       &redirect_uri={redirect-uri}
       &client_secret={client-secret}
       &code={authorization-code}
       &state={state}

```

If successful, a `(200) OK` response will be returned containing a JSON string containing `access token` related data in varying formats similiar to the below:

```auto
    {

      "access_token": "EAAkXlZBnWqyEBAIaOnwmOph34B3y9ooVBSPiMB07ut7FQcHFAXDFkwo9UcVihyiZB4DhcFqjrtHam",

      "token_type": "bearer",

      "expires_in": 5178671

    }

```

The value contained in the `access_token` field will then be submitted in the `Authorization` header with the value of `Bearer {access_token}`.

1. Add a new ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) and rename it `ExchangeCodeForToken`.

2. Add the following **$.Input** parameters:

3. Add a [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) to the **ExchangeCodeForToken** process.

4. Set the URL with an expression which will combine the input `host` and `token_endpoint` value:

5. Change the Method to `POST`.

6. Set the Body format as `URL Encoded Content`.

7. A URL encoded body field will appear:  
 ![image](https://community.linx.software/community/uploads/default/original/1X/35b33fe9b3555317f0f7585ae991f19138922506.png)  
Expand the editor and add the parameters like below:  

8. Debug the **ExchangeCodeForToken** with the correct `$.Input` values (Copy the `code` paramter from the redirection URL and add it to the Solution).

9. Add a Header to the request like below:

10. Debug the **ExchangeCodeForToken** with the correct `$.Input` values.

11. The `Response Body` should now still be a single string, but it is in `JSON` format like below:

 ![image](https://community.linx.software/community/uploads/default/original/1X/f3ac659605a18a7f1923175ee23763b3fadb6e53.png)

### Returning the access token

The current response is returned as a [StringTYP](https://linx.software/docs/reference/plugins/linx/content/string) . In order to parse the text into the respective fields, the response object needs to be imported as a CustomTYP.

 **Learn:**  
  
 See [more](https://community.linx.software/community#handling-responses-output-type-import) about importing responses.
.

Once imported, the Output type can reference this structure and the fields will be parsed.

1. Import the `Response Body` as a CustomTYP and give it the name `token`.

2. You should have a tokenTYP like the below:  

3. Set the Output type of the **CallRESTEndpoint** in the **ExchangeCodeForToken** process.

4. Add an $.Result to the **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) with a Name of `token` and the Type of `Project.Token`.

5. Add a [SetValueFNC](https://linx.software/docs/reference/plugins/linx/content/setvalue) to the end of the **ExchangeCodeForToken** process.

6. For the Target, reference `$.Result.token`.

7. For Source, reference `CallRESTEndpoint.ResponseBody`.

8. Debug the ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) again and take note of how the `Response Body` has been deserialized into the `token` object and the token returned as an output:

### Using the access token

To demonstrate how access token’s are used in a request, the below steps outline how to add an `Authorization` header with the value of `Bearer {token}`.

 **Learn:**  
  
 Find out more about bearer authentication [here](https://community.linx.software/community#authenticating-requests-bearer)

Extending the example of GitHub, a request is going to be made to the `/user` [endpoint](https://docs.github.com/en/free-pro-team@latest/rest/reference/users).

The token generated from the earlier step will be added to the `Authorization` header.

The response will contain information related to the authenticated user.

1. Create a new ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) and rename it `GetAuthenticatedUser`.

2. Add an `access_token` **$.Input** parameter.

3. Add a [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) to the **GetAuthenticatedUser** process.

4. Set the URL as `https://api.github.com/user`.

5. Expand the Headers editor and add the header with a Name of `Authorization`.

6. For the Value , use an expression like below:

7. Debug the **GetAuthenticatedUser** process, copy and paste the `access_token` from the previous step into the `$.Input.access_token`.

8. Debug the **GetAuthenticatedUser** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) again, you should recieve a `200 (OK)` like below:

9. Import the response as a CustomTYP and use it to return details from the **GetAuthenticatedUser** process. (This will be used later in the tutorial).  

Well done, you’ve successfully implemented a Generic OAuth 2.0 Provider with Linx, however, in its current state, the application is basic and requires manual intervention.

## Automating the whole flow

So far, we’ve created custom processes to successfully:

- generate an authorization URL
- make a request for an access token
- use the access token in the request

However, it still requires manual intervention for the most part.

In order to automate the entire authentication flow as well as add in some nice to haves, we are going to do the following:

- **recieve a request to generate the authorization URI**
- generate an authorization URI
- **return and redirect user-agent to the authorization URI.**
- **receive the redirection request containing the authorization code.**
- **automatically** make a request for an access token using the authorization code
- use the access token in the request

The result will be the below:

![Generic OAuth 2 Provider - Automated Flow 4](https://community.linx.software/community/uploads/default/original/1X/58833df8f3710a1e59b85d9b6a113b0952e9f77b.gif)

### Automatically re-direct users to the Authorization URI

Currently, you need to manually debug the **GenerateAuthorizationUri** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) and copy out the URL and then browse to it.

To make life easier, we are going to create a REST operation that will receive a `GET` request. When the user browses to this hosted url, the operation is executed, it will then make a call to the **GenerateAuthorizationUri** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) which will return a `uri`.

 **Learn:**  
  
 Get started with the RESTHost Tutorial [here](https://community.linx.software/community/t/resthost-get-started-hello-world/466)

In the response of the operation, the `uri` will be returned in the `Location` header along with an Status Code of `301 (Redirect)`. What this does is that when a request is made to the operation, the response redirects the `user-agent` (browser) to the authorization uri.

The advantage of this is that you can set up a static URL to navigate to (this can be a bookmark in your browser or a link on a page) - when you browse to this url, the current client identifiers will be used to generate the authorization uri.

1. Add a [RESTHostSVC](https://linx.software/docs/reference/plugins/rest/content/resthost) to your Solution.

2. Set the Base URI as `http:localhost:8080`

3. Import the below API definition:

1. Drag the **GenerateAuthorizationUri** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) from the Solution Explorer, onto the **AuthorizeRequest** operation selected in the canvas panel.

2. In order to return this `uri` in the response and redirect the user-agent to this address we first need to indicate in the response that this is a `(301) Redirect` which will make the user-agent navigate to the value provided in the `Location` header.

3. For the Target reference the whole `$.Result.Data.HttpContext` object.

4. For the Source, expand the field editor.

5. Set the StatusCode as `301`.

6. Expand the Headers editor and add a `Location` header which references the output of the **GenerateAuthorizationUri** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) like below:  
 ![Generic OAuth 2 Provider - Set Redirect](https://community.linx.software/community/uploads/default/original/1X/6fed44afb2f6213342ba9f0e8a2d29f972bd5fcd.gif)

To test the above out, we are going to locally host the REST web service and use it to make requests against.

To host a REST web service locally:

1. Right-click on the [RESTHostSVC](https://linx.software/docs/reference/plugins/rest/content/resthost) in the Solution Explorer.

2. Click **⮞ Debug**.

3. Once the Debugger has initialized, click **⮞ Start**

4. In your browser, make a request to [**THIS URI.**](http://localhost:8080/oauth/authorize)

5. If successful, you should be redirect to the GitHub authorization page to login.

![Generic OAuth 2 Provider - Make Authorize request](https://community.linx.software/community/uploads/default/original/1X/0428573a2307fe7a29194f92578c5bb194f75871.gif)

Each time you need re-generate an `authorization code`, just navigate to the `/authorize` url.

 **Tip:**  
  
Bookmark the `http://localhost:8080/oauth/authorize` uri in your web browser to make testing easier.

### Automatically request tokens after authorization.

Currently, when you authorize the application, you will be redirect to the `redirect URI` which would be:

```auto
http://localhost:8080/oauth/token?code=a3b35dbc42597a2e58e3&state=QjKcs

```

Your browser will display a `(404) Not Found` error like below:

 ![image](https://community.linx.software/community/uploads/default/original/1X/f5abfc8b0f8cf9ce78b3a8853d38771c8b101cac.png)

This is because there is no host listening on that address.

We are now going to add an **ExchangeCode** operation to our [RESTHostSVC](https://linx.software/docs/reference/plugins/rest/content/resthost) and host it on the `redirection uri`.

The operation will take in the `code` and `state` parameters as part of the `query string`.

The operation will then call the **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) from earlier.

The `code` passed in with the URL would be passed into the **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) to exchange with the Authorization Server.

Once the token has been generated, it will be passed into the **GetAuthenticatedUser** process.

A request would then be made using the token to return the currently authenticated user’s details.

These details will then be returned in the `Response Body` of the operation.

1. Add the below path and parameters to the API definition:

1. Drag the **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) from the Solution Explorer onto the **ExchangeCode** operation.

2. Configure the input values for **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) call the like below:

3. Once the **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) completes successfully, we will return a simple text message confirming the successful authentication.

4. For the Target, reference `$.Result.Data.HttpContext`.

5. Expand the Source and set the value of the Status Code field to `200`.

6. For the `Response Body`, we are just going to return a simple text message.

7. Debug the [RESTHostSVC](https://linx.software/docs/reference/plugins/rest/content/resthost) like below and navigate to the `/authorize` local endpoint from earlier:  
 ![Generic OAuth 2 Provider - Automated Flow 1](https://community.linx.software/community/uploads/default/original/1X/cc40e96667141915b5b1a5988f1a22c316c5da8e.gif)

**Full flow** (no step through):  
 ![Generic OAuth 2 Provider - Automated Flow 2](https://community.linx.software/community/uploads/default/original/1X/764416cb9e981b1aba3c1b9224eac9b88df1e2f1.gif)

### Customizing the response

To personalize the response, we are going to use the **GetAuthenticatedUser** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) to return details of the user that just granted access to the application. This is done purely to demonstrate using the access token when making a request.

1. Drag the **GetAuthenticatedUser** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) from the Solution Explorer, into the **ExchangeCode** operation, positioning it right below the **ExchangeCodeForToken** process.

2. For the `access_token` input of **GetAuthenticatedUser** , reference the token generated from the **ExchangeCodeForToken** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) like below:

3. We now use the user details returned from the **GetAuthenticatedUser** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) to personaize the response message.

## Storing and retrieving the access token

In its current state, the Solution successfully generates and uses the access token. However, to re-authorize and generate a new token each time a request is made is impractical. As Linx does not persist data unless stored as a setting, you will need to store the token in a datasource of some kind (database, text file), in order to retrieve for later use in requests.

To demonstrate the concept, we are going to create a generic ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) that will store the access token object in a local text file.

 **Note:**  
  
Typically, access tokens would be stored in a database, for the use in this demonstration we will use a file instead as some users may have not set up a database

We are then going to create a generic ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) that will return the token details when they are needed n a request.

### Logging the token

1. Create a new ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) and rename it `LogToken`.

2. For the **$.Inputs** , add a `token` field and reference the `Project.token` object as the Type.

3. Within the **LogToken** process, add a [TextFileWriteFNC](https://linx.software/docs/reference/plugins/file/content/textfilewrite) .

4. For the File path we are going to create a ⚙ $.Setting value which will store the location of the file.

5. For the Contents. we want to store the whole `token` object as plain text.

6. For the Contents of the **TextFileWrite** , reference `stringifyToken`.

7. Ensure the File exists is set to `Overwrite`.

 ![image](https://community.linx.software/community/uploads/default/original/1X/67e143d0335d45b8d721c6b34cb0d213ec20ccc6.png)

You are then able to make a ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) call to the **LogToken** process, in the **ExchangeCode** operation, passing in the token that was just generated (i.e. `ExchangeCodeForToken.token`):

 ![image](https://community.linx.software/community/uploads/default/original/1X/5e37f1cf28d6962762d36b8bf3e44973f84cc2a3.png)

Now, if you re-initiate the whole flow again, the token response object will be logged in the “token.txt” text file:

 ![image](https://community.linx.software/community/uploads/default/original/1X/761c6cee1454bdf313bf1d379a6b1f3497eec8ea.png)

### Retrieving the token

By storing the whole JSON string of the object, we are able to read the contents back out and assign them directly into our tokenTYP, this makes working with the individual fields easier.

We are now going to build a ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) that will read the contents from “token.txt”, assign it to the tokenTYP and return the details. This ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) can then be called from other processes when a request is made. The latest stored token will be returned and then can be used in the `Authorization` header.

1. Create a new ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) and rename it `RetrieveToken`.

2. For the **$.Result** , add a `token` field and reference the `Project.token` object as the Type.

3. Within the **RetrieveToken** process, add a [TextFileReadFNC](https://linx.software/docs/reference/plugins/file/content/textfileread) .

4. For the File path, reference the same $.Settings value that was used when writing to the file (i.e. `$.Settings.token_log_path`).

5. For the Return options, select `Complete`.

6. As the JSON stored in the file maps directly to the `token`TYP, we can use a [SetValueFNC](https://linx.software/docs/reference/plugins/linx/content/setvalue) to assign the output of the **TextFileRead** directly to the `$.Result.token` of the **RetrieveToken** process.  

You are then able to call **RetrieveToken** wherever you need the current access token to make a request.

To demonstrate:

1. Remove the `$.Input.access_token` field for the **GetAuthenticatedUser** process.
2. A validation error should appear as the `$.Input.access_token` field no longer exists. Instead of passing in the current access token value to the **GetAuthenticatedUser** process, we can just make a call inside of the **GetAuthenticatedUser** ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) to the **RetrieveToken** process.  
 ![image](https://community.linx.software/community/uploads/default/original/1X/2f89687c7f8b615f20e259c0777b2c5177de1cb7.png)
3. We can then use the token details returned for the `Authorization` header of the **CallRESTEndpoint** like below:

```auto
="Bearer " + RetrieveToken.token.access_token

```

Now when re-initiate the flow, the generated token will be logged in a file. When the user details are requested, the latest token details are retrieved from the local text file and submitted with the request.

## You’re set to go!

If you’ve followed the above guide, you should have a better understanding of the OAuth 2.0 flow as well as have a practical understanding of building a basic OAuth 2.0 authenticator with Linx. Hopefully, you should now be able to connect to your API of choice using the above tutorial as a base template.

Look out for more samples and post in the Linx Community.

 **Need help?**  
  
 For personal support queries, please contact **support@linx.software** or reply on this article.
