# Authorization

> You can use an OAuth access token to acces the API.

Depending on your use case (we will help in determining what you need), you will use one of the following:
1. [Personal Access Token](/authentication?id=personal-access-token): for global access to an entire company.
2. [Authorization Code with PKCE](/authentication?id=authorization-code-with-pkce): for access to specific producers.

If you already have an access token, skip to [Using Access Tokens](/authentication?id=using-access-tokens)

## Personal Access Token
We can give you access to an entire company's data as long as the company approves it. In this case, we will assign a long-living personal access token to a [Employee](/objects?id=employee) account, which gives you access to the company and all its data.

Email us at connect@barchart.com to get started.

## Authorization Code with PKCE
When you want to display specific customer data within your app, you will use the Proof Key for Code Exchange (PKCE) flow. If you're familiar with OAuth, or at least using it via Google, Facebook, etc., this is the typical login flow you would see where the user must explicitly give your application access to their data.

> Run through a demo of how the PKCE flow works at [oauth.com](https://www.oauth.com/playground/authorization-code-with-pkce.html).

### Obtain an OAuth Client
Email us at connect@barchart.com or call us at 877-247-4394.

> When requesting your client, be sure to specify a `redirect_uri`, a URL that you control that we can redirect back to after a user authorizes your application. You will need this in Step 4 of the following section. At any point, you can also request to change this or add more URI's.

### Obtain an Access Token
Before accessing user data, you must obtain an access token for that user. In simple terms, your application will redirect to us and ask the user to log in and authorize your application, then you will be able to request an access token.

#### OAuth Client Libraries
We recommend that you use one of the many open source OAuth client libraries. See [https://oauth.net/code/](https://oauth.net/code/) for a list of available clients in numerous languages.

#### Implementing Yourself
At the same time, there is nothing overly complicated about implementing the authorization flow yourself. Below is an outline on how you can do this yourself.

##### 1. Create a Code Verifier
The `code_verifier` should be a random string between 43 and 128 characters. It can contain letters, numbers and `-`, `.`, `_`, `~` as defined in the PKCE specification.

ABNF for `code_verifier`:
```
code-verifier = 43*128unreserved
   unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
   ALPHA = %x41-5A / %x61-7A
   DIGIT = %x30-39
```

> You should save the `code_verifier` in your application session to use in Step 5.

##### 2. Create a Code Challenge
Next, you need to create a `code_challenge` derived from the `code_verifier` in Step 1. The `code_challenge` should be a base64-encoded string with URL and filename-safe characters only. The trailing `=` characters should be removed and no line breaks, whitespace, or other characters should be present.

Your `code_challenge` should look like this:
```
code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
```

##### 3. Create a State
The `state` should be a random string of 40 or more characters. This is used as a session ID of sorts to ensure your application and our server are communicating about the same authorization request.

> You should save the `state` in your application session to use in Step 5.

##### 4. Send an Authorization Request
We now have everything necessary to create an authorization request. You will send your `code_challenge` and `state` along with your `client_id`, `redirect_uri`, and [`scope`](/authentication?id=scope) to us so the user can authorize your application.

You should direct your application to the specific company the user wants to connect their account to. For a company with a `displayId` of `ABC`, you will send your authorization request to: https://abc.cmdtymarketplace.com/oauth/authorize

> Get the `displayId` for the company using the [`companies`](/queries?id=companies) query.

Here is an example:
```
https://{displayId}.cmdtymarketplace.com/oauth/authorize?
    response_type=code&
    client_id=YOUR_CLIENT_ID&
    redirect_uri=YOUR_REDIRECT_URI&
    scope=YOUR_SCOPE&
    state=YOUR_STATE&
    code_challenge=YOUR_CODE_CHALLENGE&
    code_challenge_method=S256
```

If the user authorizes your application, we will respond back to your `redirect_uri` with a `code` and your `state`.

###### Scope
The `scope` tells us what permissions you want on the user's account. You can request the following scopes:

Scope|Description
-|-
`accounts`|Read only access to accounts, balances, contracts, scale tickets, and settlements.
`offers`|Read only access to the customer's offers.
`offers.write`|Create new and update existing offers on the customer's behalf.
`signatures`|Read only access to the customer's signatures.
`signatures.write`|Sign contracts on the customer's behalf.

> Multiple scopes should be delimited by spaces.

##### 5. Request an Access Token
If the user authorizes your application, you can use the `code` returned from us in the previous step and your `code_verifier` from Step 1 to request an `access_token`.

First, you should confirm that the `state` we send back is identical to the `state` that you sent. Then you can `POST` to the specific company's `/oauth/token` endpoint. From our `displayId=ABC` example earlier, the endpoint will look like this: https://abc.cmdtymarketplace.com/oauth/token

Here is an example:
```http
POST /oauth/token HTTP/1.1
Host: {displayId}.cmdtymarketplace.com
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache

{
    "grant_type": "authorization_code",
    "client_id": "YOUR_CLIENT_ID",
    "redirect_uri": "YOUR_REDIRECT_URI",
    "code_verifier": "YOUR_CODE_VERIFIER",
    "code": "CODE_RETURNED_FROM_STEP_4"
}
```

That's it! You will receive a response like the following:
```json
{
    "token_type": "Bearer",
    "expires_in": 36000,
    "access_token": "USER_ACCESS_TOKEN",
    "refresh_token": "USER_REFRESH_TOKEN"
}
```

> Save the user's `refresh_token` in secure long-term storage in order to stay authorized for a longer period of time.

### Refresh an Access Token
Access tokens retrieved via the PKCE flow have limited lifetimes, however with each `access_token`, you will also receive a `refresh_token`. After an unauthorized request, you can use the `refresh_token` to retrieve a brand new `access_token`.

Here is an example:
```http
POST /oauth/token HTTP/1.1
Host: {displayId}.cmdtymarketplace.com
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache

{
    "grant_type": "refresh_token",
    "refresh_token": "YOUR_REFRESH_TOKEN",
    "client_id": "YOUR_CLIENT_ID"
}
```

> Refresh tokens, like access tokens, have limited lifetimes, but the lifetime is much longer. If your `refresh_token` expires, you will need to send the user back through the [authorization process](/authentication?id=obtain-an-access-token) to obtain a new `access_token`.

### Troubleshooting
The error messages returned can be intentionally vague. Here are some things to keep in mind if you have problems.

#### Headers
Make sure your requests to the `/oauth/token` endpoints contain both the `Content-Type: application/json` and `Accept: application/json` headers.

#### Redirect URI
Make sure your `redirect_uri` matches one of the URI's you have asked us to configure.

#### Scopes
Check that the `scope`(s) specified are valid, and when using more than one, they are delimited by *spaces*.

## Using Access Tokens
To use an access token, simply specify it as a `Bearer` token in your request's `Authorization` header.

Example using cURL:
```bash
curl -H 'Content-Type: application/json' -H 'Authorization: Bearer <access_token>' -X POST -d " \
 { \
   \"query\": \"query { viewer { offers { id } } }\" \
 } \
" https://connect.api.barchart.com/graphql
```

## Security
### JavaScript Applications
Since you cannot securely store access and refresh tokens in the browser, you should create a proxy to connect.api.barchart.com for your use of the API.
