2018-01-15 16:41:42 +01:00
# Authentication
2017-12-08 12:27:48 +01:00
2019-02-11 09:44:19 +08:00
This Authentication API requires the Users & Permissions plugin which comes with Strapi, installed by default.
2018-04-03 18:14:56 +02:00
2019-02-11 09:44:19 +08:00
## Token usage
2017-12-08 12:27:48 +01:00
2019-03-02 13:56:26 +01:00
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.
2017-12-08 12:27:48 +01:00
#### Usage
2019-02-11 09:44:19 +08:00
- The `token` variable is the `data.jwt` received when login in or registering.
2017-12-08 12:27:48 +01:00
```js
2018-10-28 08:15:31 +01:00
import axios from 'axios';
2019-02-11 09:44:19 +08:00
const token = 'YOUR_TOKEN_HERE';
2018-10-28 08:15:31 +01:00
// Request API.
2019-02-11 09:44:19 +08:00
axios
.get('http://localhost:1337/posts', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
// Handle success.
console.log('Data: ', response.data);
})
.catch(error => {
// Handle error.
console.log('An error occurred:', error);
});
```
## Registration
2019-03-02 13:56:26 +01:00
Creates a new user in the database with a default role as 'registered'.
2019-02-11 09:44:19 +08:00
#### Usage
```js
import axios from 'axios';
// Request API.
// Add your own code here to customize or restrict how the public can register new users.
2018-10-28 08:15:31 +01:00
axios
.post('http://localhost:1337/auth/local/register', {
2018-01-22 10:41:31 +07:00
username: 'Strapi user',
2017-12-08 12:27:48 +01:00
email: 'user@strapi .io',
password: 'strapiPassword'
2018-10-28 08:15:31 +01:00
})
.then(response => {
// Handle success.
2017-12-08 12:27:48 +01:00
console.log('Well done!');
2018-10-28 08:15:31 +01:00
console.log('User profile', response.data.user);
console.log('User token', response.data.jwt);
})
.catch(error => {
// Handle error.
2017-12-08 12:27:48 +01:00
console.log('An error occurred:', error);
2018-10-28 08:15:31 +01:00
});
2017-12-08 12:27:48 +01:00
```
2018-10-28 08:15:31 +01:00
## Login
2017-12-08 12:27:48 +01:00
2019-02-11 09:44:19 +08:00
Submit the user's identifier and password credentials for authentication. When the authentication is successful, the response data returned will have the users information along with a jwt authentication token.
2017-12-08 12:27:48 +01:00
2018-01-12 15:48:14 +01:00
#### Local
2017-12-08 12:27:48 +01:00
- The `identifier` param can either be an email or a username.
```js
2018-10-28 08:15:31 +01:00
import axios from 'axios';
// Request API.
axios
.post('http://localhost:1337/auth/local', {
identifier: 'user@strapi .io',
password: 'strapiPassword'
})
.then(response => {
// Handle success.
2017-12-08 12:27:48 +01:00
console.log('Well done!');
2018-10-28 08:15:31 +01:00
console.log('User profile', response.data.user);
console.log('User token', response.data.jwt);
})
.catch(error => {
// Handle error.
2017-12-08 12:27:48 +01:00
console.log('An error occurred:', error);
2018-10-28 08:15:31 +01:00
});
2017-12-08 12:27:48 +01:00
```
2018-01-12 15:48:14 +01:00
## Providers
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. By default,
2018-07-31 03:40:05 -07:00
Strapi comes with the following providers:
- [Discord ](https://github.com/strapi/strapi-examples/blob/master/login-react/doc/discord_setup.md )
2018-06-15 15:38:09 +02:00
- [Facebook ](https://github.com/strapi/strapi-examples/blob/master/login-react/doc/fb_setup.md )
- [Google ](https://github.com/strapi/strapi-examples/blob/master/login-react/doc/google_setup.md )
- [Github ](https://github.com/strapi/strapi-examples/blob/master/login-react/doc/github_setup.md )
- [Twitter ](https://github.com/strapi/strapi-examples/blob/master/login-react/doc/twitter_setup.md )
[👀 See our complete example with detailed tutorials for each provider (with React) ](https://github.com/strapi/strapi-examples/tree/master/login-react )
---
2018-01-12 15:48:14 +01:00
2019-02-11 09:44:19 +08:00
Set your providers credentials in the admin interface (Plugin Users & Permissions > Providers).
2018-03-12 17:15:20 +01:00
Then update and enable the provider you want use.
2018-01-12 15:48:14 +01:00
2019-02-11 09:44:19 +08:00
To authenticate the user, use the GET method to request the url, `/connect/:provider` . eg: `GET /connect/facebook`
2018-01-12 15:48:14 +01:00
2019-02-11 09:44:19 +08:00
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.
2018-01-12 15:48:14 +01:00
Response payload:
2018-10-28 08:15:31 +01:00
```json
2018-01-12 15:48:14 +01:00
{
"user": {},
"jwt": ""
}
```
2018-10-28 08:15:31 +01:00
## Forgotten password
2017-12-08 12:27:48 +01:00
This action sends an email to a user with the link of you reset password page. This link contains an URL param `code` which is required to reset user password.
#### Usage
- `email` is your user email.
2018-09-16 21:52:26 +02:00
- `url` is the url link that user will receive. After the user triggers a new password reset,
it is used to redirect the user to the new-password form.
2017-12-08 12:27:48 +01:00
```js
2018-10-28 08:15:31 +01:00
import axios from 'axios';
// Request API.
axios
.post('http://localhost:1337/auth/forgot-password', {
2018-01-22 10:41:31 +07:00
email: 'user@strapi .io',
2018-09-16 21:52:26 +02:00
url: 'http:/localhost:1337/admin/plugins/users-permissions/auth/reset-password'
2018-10-28 08:15:31 +01:00
})
.then(response => {
// Handle success.
2017-12-08 12:27:48 +01:00
console.log('Your user received an email');
2018-10-28 08:15:31 +01:00
})
.catch(error => {
// Handle error.
2017-12-08 12:27:48 +01:00
console.log('An error occurred:', error);
2018-10-28 08:15:31 +01:00
});
2017-12-08 12:27:48 +01:00
```
2018-10-28 08:15:31 +01:00
## Password reset
2017-12-08 12:27:48 +01:00
This action will reset the user password.
#### Usage
- `code` is the url params received from the email link (see forgot password)
```js
2018-10-28 08:15:31 +01:00
import axios from 'axios';
// Request API.
axios
.post('http://localhost:1337/auth/reset-password', {
2018-01-22 10:41:31 +07:00
code: 'privateCode',
password: 'myNewPassword',
2017-12-08 12:27:48 +01:00
passwordConfirmation: 'myNewPassword'
2018-10-28 08:15:31 +01:00
})
.then(response => {
// Handle success.
console.log('Your user\'s password has been changed.');
})
.catch(error => {
// Handle error.
2017-12-08 12:27:48 +01:00
console.log('An error occurred:', error);
2018-10-28 08:15:31 +01:00
});
2017-12-08 12:27:48 +01:00
});
```
2018-01-26 18:04:39 +01:00
2018-10-28 08:15:31 +01:00
## User object in Strapi context
2018-09-16 21:52:26 +02:00
The `user` object is available to successfully authenticated requests.
2018-03-23 21:29:23 +10:00
#### Usage
- The authenticated `user` object is a property of `ctx.state` .
```js
create: async (ctx) => {
const { _id } = ctx.state.user
const depositObj = {
...ctx.request.body,
depositor: _id
}
const data = await strapi.services.deposit.add(depositObj);
// Send 201 `created`
ctx.created(data);
}
```
2018-10-28 08:15:31 +01:00
## Adding a new provider
2018-08-27 16:16:16 +02:00
2018-09-16 21:52:26 +02:00
To add a new provider on Strapi, you will need to perform changes onto the following files:
2018-08-27 16:16:16 +02:00
```
packages/strapi-plugin-users-permissions/services/Providers.js
packages/strapi-plugin-users-permissions/config/functions/bootstrap.js
packages/strapi-plugin-users-permissions/admin/src/components/PopUpForm/index.js
packages/strapi-plugin-users-permissions/admin/src/translations/en.json
```
We will go step by step.
2018-09-16 21:52:26 +02:00
### Configure your Provider Request
2019-02-11 09:44:19 +08:00
Configure the new provider in the `Provider.js` file at the `getProfile` function.
2018-08-27 16:16:16 +02:00
2019-02-11 09:44:19 +08:00
The `getProfile` takes three params:
2018-08-27 16:16:16 +02:00
1. provider :: The name of the used provider as a string.
2. query :: The query is the result of the provider callback.
2018-09-16 21:52:26 +02:00
3. callback :: The callback function who will continue the internal Strapi login logic.
2018-08-27 16:16:16 +02:00
2019-02-11 09:44:19 +08:00
Here is an example that uses the `discord` provider.
2018-08-27 16:16:16 +02:00
#### 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'
}
}
}
}
}
});
2018-09-16 21:52:26 +02:00
}
2018-08-27 16:16:16 +02:00
```
2019-02-11 09:44:19 +08:00
This code creates a `Purest` object that gives us a generic way to interact with the provider's REST API.
2018-08-27 16:16:16 +02:00
2019-02-11 09:44:19 +08:00
For more specs on using the `Purest` module, please refer to the [Official Purest Documentation ](https://github.com/simov/purest/tree/2.x )
2018-08-27 16:16:16 +02:00
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 ).
2019-02-11 09:44:19 +08:00
#### Retrieve your user's information:
For our discord provider it will look like:
2018-08-27 16:16:16 +02:00
```js
discord.query().get('users/@me ').auth(access_token).request((err, res, body) => {
if (err) {
callback(err);
} else {
// Combine username and discriminator because discord username is not unique
2018-10-28 08:15:31 +01:00
const username = `${body.username}#${body.discriminator}` ;
2018-08-27 16:16:16 +02:00
callback(null, {
2018-10-28 08:15:31 +01:00
username,
2018-08-27 16:16:16 +02:00
email: body.email
});
}
});
break;
}
```
2018-09-16 21:52:26 +02:00
Here is the next part of our switch. Now that we have properly configured our provider, we want to use it to retrieve
user information.
2018-08-27 16:16:16 +02:00
2018-09-16 21:52:26 +02:00
Here you see the real power of `purest` , you can simply make a get request on the desired URL, using the `access_token`
from the `query` parameter to authenticate.
2018-08-27 16:16:16 +02:00
That way, you should be able to retrieve the user info you need.
2018-09-16 21:52:26 +02:00
Now, you can simply call the `callback` function with the username and email of your user. That way, strapi will be able
to retrieve your user from the database and log you in.
2018-08-27 16:16:16 +02:00
#### Configure the new provider model onto database
2018-09-16 21:52:26 +02:00
Now, we need to configure our 'model' for our new provider. That way, our settings can be stored in the database, and
managed from the admin panel.
2018-08-27 16:16:16 +02:00
2019-02-11 09:44:19 +08:00
Open the file `packages/strapi-plugin-users-permissions/config/functions/bootstrap.js`
2018-08-27 16:16:16 +02:00
2019-02-11 09:44:19 +08:00
Add the fields your provider needs into the `grantConfig` object.
2018-08-27 16:16:16 +02:00
For our discord provider it will look like:
```js
discord: {
enabled: false, // make this provider disabled by default
icon: 'comments', // The icon to use on the UI
key: '', // our provider app id (leave it blank, you will fill it with the content manager)
secret: '', // our provider secret key (leave it blank, you will fill it with the content manager)
callback: '/auth/discord/callback', // the callback endpoint of our provider
scope: [ // the scope that we need from our user to retrieve infos
'identify',
'email'
]
},
```
<!-- #### Tests -->
<!-- TODO Add documentation about how to configure unit test for the new provider -->
### Configure frontend for your new provider
2019-02-11 09:44:19 +08:00
To make the new provider available on the front end of the application,
edit `packages/strapi-plugin-users-permissions/admin/src/components/PopUpForm/index.js`
Add the new provider info. For our discord provider it will look like:
2018-08-27 16:16:16 +02:00
```js
case 'discord':
return `${strapi.backendURL}/connect/discord/callback` ;
```
2019-02-11 09:44:19 +08:00
### Add language translation
Add the language translation in `packages/strapi-plugin-users-permissions/admin/src/translations/en.json`
2018-08-27 16:16:16 +02:00
```js
2018-10-28 08:15:31 +01:00
'PopUpForm.Providers.discord.providerConfig.redirectURL': 'The redirect URL to add in your Discord application configurations',
2018-08-27 16:16:16 +02:00
````
2019-02-11 09:44:19 +08:00
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.
2018-03-23 21:29:23 +10:00
2018-01-26 18:04:39 +01:00
## Email templates
[See the documentation on GitHub ](https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/docs/email-templates.md )