This plugin provides a way to protect your API with a full authentication process based on JWT. This plugin comes also with an ACL strategy that allows you to manage the permissions between the groups of users.
When this plugin is installed, it adds an access layer on your application.
The plugin uses [`jwt token`](https://en.wikipedia.org/wiki/JSON_Web_Token) to authenticate users.
Each time an API request is sent, the server checks if an `Authorization` header is present and verifies if the user making the request has access to the resource.
To do so, your JWT contains your user ID and we are able to match the group your user is in and at the end to know if the group allows access to the route.
## Manage role permissions
### Public role
This role is used when you receive a request that doesn't have an `Authorization` header.
If you allow some permissions in this role, everybody will be able to access the endpoints you selected.
This is common practice to select `find` / `findOne` endpoints when you want your front-end application to access all the content without developing user authentication and authorization.
### Authenticated role
This is the default role that is given to every **new user** if no role is provided at creation. In this role you will be able to define routes that a user can access.
### Permissions management
By clicking on the **Role** name, you will be able to see all functions available in your application (and these functions are related to a specific route)
If you check a function name, it makes this route accessible by the current role you are editing.
On the right sidebar you will be able to see the URL related to this function.
### Update the default role
When you create a user without a role or if you use the `/auth/local/register` route, the `authenticated` role is given to the user.
To change the default role, go to the `Advanced settings` tab and update the `Default role for authenticated users` option.
## Authentication
### Token usage
A jwt token may be used for making permission-restricted API requests. To make an API request as a user, place the jwt token into an `Authorization` header of the GET request. A request without a token, will assume the `public` role permissions by default. Modify the permissions of each user's role in admin dashboard. Authentication failures return a 401 (unauthorized) error.
#### Usage
- The `token` variable is the `data.jwt` received when logging in or registering.
You can configure option for the JWT generation by creating `extensions/users-permissions/config/security.json` file.
We are using [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken) to generate the JWT.
Available options:
-`expiresIn`: expressed in seconds or a string describing a time span zeit/ms.<br>
Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").
Submit the user's identifier and password credentials for authentication. When the authentication is successful, the response data returned will have the user's information along with a jwt authentication token.
#### Local
- The `identifier` param can either be an **email** or a **username**.
Thanks to [Grant](https://github.com/simov/grant) and [Purest](https://github.com/simov/purest), you can easily use OAuth and OAuth2 providers to enable authentication in your application.
Before setting up a provider, you'll need to install the `ngrok` package globally to work with providers that don't allow `localhost` redirect URIs.
In the following examples, the client app will be the [react login examples app](https://github.com/strapi/strapi-examples/tree/master/login-react). It will be running on `http://localhost:3000`.
:::: tabs
::: tab GitHub
#### Setup the server
Use `ngrok` to serve the frontend app.
```
ngrok http 3000
```
#### Github configuration
- Visit the OAuth Apps list page <br> [https://github.com/settings/developers](https://github.com/settings/developers)
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- Click on **OAuth 2.0 Client IDs** name of the client you just created
#### Strapi configuration
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- **Tell us how this app will be used**: - here write a message enough long -
To access the Consumer API keys:
- Click on **Keys and tokens** tab
#### Strapi configuration
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- **The redirect URL to your front-end app**: `https://65e60559.ngrok.io/connect/twitter`
:::
::: tab Discord
#### Discord configuration
- Visit the Apps list page on the developer portal <br> [https://discordapp.com/developers/applications/](https://discordapp.com/developers/applications/)
- Click on **New application** button
- Fill the **name** and create
- Click on **OAuth2** in the left menu
- And click on **Add redirect** button
- Fill the **Redirect** input with `http://localhost:1337/connect/discord/callback` URL and save
To access the Consumer API keys:
- Click on **General information** in the left menu
#### Strapi configuration
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- Then generate a new **Client Secret** with the **New Secret** button
#### Strapi configuration
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
Make sure your Application information are well completed.
#### Strapi configuration
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- Visit the User Permissions provider settings page <br> [http://localhost:1337/admin/plugins/users-permissions/providers](http://localhost:1337/admin/plugins/users-permissions/providers)
- **The redirect URL to your front-end app**: `http://localhost:3000/connect/vk`
:::
::::
Set your providers credentials in the admin interface (Plugin > Roles & Permissions > Providers).
Then update and enable the provider you want to use.
To authenticate the user, use the GET method to request the url, `/connect/:provider`. eg: `GET /connect/facebook`.
You can also pass a custom callback url instead of using the default registered provider callback, by passing `callback` in the query. eg: `GET /connect/facebook?callback=https://my-frontend.com/en/auth/facebook`.
After authentication, create and customize your own redirect callback at `/auth/:provider/callback`. The `jwt` and `user` data will be available in a .json response.
In production, make sure the `url` config property is set. Otherwise the validation link will redirect to `localhost`. More info on the config [here](../concepts/configurations.html#server).
After having registered, if you have set **Enable email confirmation** to **ON**, the user will receive a confirmation link by email. The user has to click on it to validate his/her registration.
_Example of the confirmation link:_ `https://yourwebsite.fr/auth/email-confirmation?confirmation=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaWF0IjoxNTk0OTgxMTE3LCJleHAiOjE1OTc1NzMxMTd9.0WeB-mvuguMyr4eY8CypTZDkunR--vZYzZH6h6sChFg`
If these files don't exist you will need to copy from your `node_modules` or the Strapi mono-repo. You can see the [plugin extensions](../concepts/customization.md#plugin-extensions) for more information as to how this works
We will go step by step.
### Configure your Provider Request
Configure the new provider in the `Provider.js` file at the `getProfile` function.
The `getProfile` takes three params:
- **provider**: The name of the used provider as a string.
- **query**: The query is the result of the provider callback.
- **callback**: The callback function who will continue the internal Strapi login logic.
Here is an example that uses the `discord` provider.
### Configure your oauth generic information
```js
case 'discord': {
const discord = new Purest({
provider: 'discord',
config: {
'discord': {
'https://discordapp.com/api/': {
'__domain': {
'auth': {
'auth': {'bearer': '[0]'}
}
},
'{endpoint}': {
'__path': {
'alias': '__default'
}
}
}
}
}
});
}
```
This code creates a `Purest` object that gives us a generic way to interact with the provider's REST API.
You may also want to take a look onto the numerous already made configurations [here](https://github.com/simov/purest-providers/blob/master/config/providers.json).
Add the language translation in `packages/strapi-plugin-users-permissions/admin/src/translations/en.json`
```js
'PopUpForm.Providers.discord.providerConfig.redirectURL': 'The redirect URL to add in your Discord application configurations',
```
These two change will set up the popup message that appears in the UI. That's it, now you should be able to use your new provider.
### Rebuild the Admin Panel
Please see the following [documentation](../admin-panel/customization.md#build) on rebuilding the admin panel.
## Templating emails
By default, this plugin comes with only two templates (reset password and email address confirmation) at the moment. More templates will come later. The templates use Lodash's template() method to populate the variables.
You can update these templates under **Plugins** > **Roles & Permissions** > **Email Templates** tab in the admin panel.
### Reset Password
-`USER` (object)
-`username`
-`email`
-`TOKEN` corresponds to the token generated to be able to reset the password.
-`URL` is the link where the user will be redirected after clicking on it in the email.
### Email address confirmation
-`USER` (object)
-`username`
-`email`
-`CODE` corresponds to the CODE generated to be able confirm the user email.
-`URL` is the Strapi backend URL that confirms the code (by default `/auth/email-confirmation`).
## Security configuration
JWT tokens can be verified and trusted because the information is digitally signed. To sign a token a _secret_ is required. By default Strapi generates one that is stored in `./extensions/users-permissions/config/jwt.js`. This is useful during development but for security reasons it is **recommended** to set a custom token via an environment variable `JWT_SECRET` when deploying to production.
By default you can set a `JWT_SECRET` environment variable and it will be used as secret. If you want to use another variable you can update the configuration file.