# Authentication API

## Overview

This document guides you through how to obtain access tokens required for Husqvarna Group's REST APIs. The Authentication API supports multiple OAuth 2.0 grant types to secure your applications.

You can read more about different authorization `grant_type` provided for your application to access the API from <a href="/docs/api">API Documentation</a>.

- [Client credentials grant](#client-credentials-grant) - For own user/application.
- [Authorization Code Grant](#authorization-code-grant) - For applications serving multiple users.
- [Refresh token grant](#refreshing-a-token)- For extending sessions.

## Prerequisites for provided examples

For provided examples we use [Node.js](https://nodejs.org/en/) (v22.14.0+) and [Fetch API](https://nodejs.org/en/learn/getting-started/fetch)

### Client Credentials Grant

When you login with `client_credentials` you will receive a token for your own user (the user who created the Developer Portal application).

> **SECURITY NOTE**: The `client_id` and `client_secret` are sensitive credentials that should never be exposed to users or included in client-side code.

```javascript
const clientId = process.env.APPLICATION_KEY;
const clientSecret = process.env.APPLICATION_SECRET;

async function login() {
  const params = new URLSearchParams();
  params.set('grant_type', 'client_credentials');
  params.set('client_id', clientId);
  params.set('client_secret', clientSecret);

  const res = await fetch('https://api.authentication.husqvarnagroup.dev/v1/oauth2/token', {
    method: 'POST',
    body: params
  });

  if (!res.ok) {
    throw new Error(res.statusText);
  }

  return res.json();
}
```
Given that you have defined `APPLICATION_KEY` and `APPLICATION_SECRET` in environment variables you should get the following token object after calling the `login` method above:

```javascript
{
  access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...xwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
  // The scope of the token (what you are allowed to do)
  scope: 'iam:read',
  // The expire time in seconds for the access token
  expires_in: 3600,
  provider: 'husqvarna',
  user_id: '610b0aee-3d4f-3ac6-bd8e-786deafa94ce',
  token_type: 'Bearer'
}
```

In the token object above we see that we have the properties:

- `access_token`
- `expires_in`
- `user_id`

In the example above the `access_token` expires after `3600` seconds.
The [Authentication API](/apis/Authentication+API) will send a `HTTP 401` if the `access_token` is invalid, or a `HTTP 404` if the `access_token` is expired.
That's when it is time to use the `client_credentials` again.

### Authorization Code Grant

The `client_credentials` grant is intended only for your own user, the `authorization_code` grant type is a bit more secure and intended for *everyone else* that wants to use your application.

You can get a more detailed explanation for the `authorization_code` flow steps in <a href="/docs/api">API Documentation</a>. You can also refer below for a brief snapshot of the same steps.

1. To begin an Authorization Code flow, go to the login URL for the Authentication API.

In URL, replace the `APP_KEY` with your application key (clientId) and the `REDIRECT_URI` with your redirect url for your application.


> **Note** that the redirect URL needs to be a valid URL, since the Authentication API will redirect back to the URL.


```bash
"https://api.authentication.husqvarnagroup.dev/v1/oauth2/authorize?client_id=<APP KEY>&redirect_uri=<REDIRECT_URI>"
```

2. After a successful login, a user can review your application and select `Authorize` or `Deny` access to the application.

3. Once the application is authorized by the user, the user will be redirected to the provided `redirect_uri` endpoint.

```bash
"<REDIRECT_URI>?code=<AUTHORIZATION_CODE>&state=<STATE>"
```

4. Once you have authorized the application using grant type `authorization_code`, a new `access_token` can be obtained by using the `authorization_code`.

  ```javascript
  const clientId = process.env.APPLICATION_KEY;
  const clientSecret = process.env.APPLICATION_SECRET;
  const redirectUri = 'insert-redirect-uri-entered-for-grant-type-code';

  async function getAccessTokenByCode(authorizationCode, state) {
    const params = new URLSearchParams();
    params.set('grant_type', 'authorization_code');
    params.set('code', authorizationCode);
    params.set('redirect_uri', redirectUri);
    params.set('client_id', clientId);
    params.set('client_secret', clientSecret);
    params.set('state', state);

    const res = await fetch(`https://api.authentication.husqvarnagroup.dev/v1/oauth2/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: params
    });

    if (!res.ok) {
      throw new Error(res.statusText);
    }

    return res.json();
  }
  ```

Given that you have defined `APPLICATION_KEY` and `APPLICATION_SECRET` in environment variables and replaced the values for `authorization_code`, `redirect_uri` and `state` you should get a token object that looks something like.

```javascript
{
  access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...xwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
  // Refresh token to get a new access token, so the user does not need to enter their credentials again
  refresh_token: '55021ad9-6451-48eb-5ad2-1c2b53b7dca9',
  // The scope of the token (what you are allowed to do)
  scope: 'iam:read',
  // The expire time in seconds for the access token
  expires_in: 3600,
  provider: 'husqvarna',
  user_id: '610b0aee-3d4f-3ac6-bd8e-786deafa94ce',
  token_type: 'Bearer'
}
```

### Refreshing a token

Refresh tokens is only used for the `authorization_code` grant. A new `access_token` can be obtained by using the `refresh_token` grant.

#### Example

```javascript
const clientId = process.env.APPLICATION_KEY;

async function loginWithRefreshToken(refreshToken) {
  const params = new URLSearchParams();
  params.set('grant_type', 'refresh_token');
  params.set('client_id', clientId);
  params.set('refresh_token', refreshToken);

  const res = await fetch('https://api.authentication.husqvarnagroup.dev/v1/oauth2/token', {
    method: 'POST',
    body: params
  });

  if (!res.ok) {
    throw new Error(res.statusText);
  }

  return res.json();
}
```
The `refresh_token` is currently valid for `86400` seconds (1 day).
If the `refresh_token` isn't used before is expires, the user needs to re-enter their credentials as well as described in [Authorization Code Grant](#authorization-code-grant).

### Invalidating a Token
For security reasons, you should always invalidate the token when it's not needed anymore.

```javascript
async function logout(accessToken) {
  const params = new URLSearchParams();
  params.set('token', accessToken);

  return fetch('https://api.authentication.husqvarnagroup.dev/v1/oauth2/revoke', {
    method: 'POST',
    headers: { Authorization: `Bearer ${accessToken}` },
    body: params
  });
}
```

The token in the body is the token that will be revoked. The token in the Authorization header is used to authorize the user
and does not need to be the same as the token in the body.

### Get the Current Logged In User

Since the `access_token` is a JWT token, it can be decoded and in the decoded token it is possible
to see some user information.

## Limits
We currently have the following limits on the Authentication API:

- Max 3 access tokens for a user and client.
- If more than 10 invalid login attempts are performed in a 5 minute window, we will lock the account for 30 minutes.


## Summary
An access token can be obtained for your application and must be used to communicate with our REST APIs.
Users should re-use the access token until it expires instead of creating new tokens each time.
