This plugin provides a full authentication process based on JSON Web Tokens (JWT)(opens new window) to protect your API. It also provides an access-control list (ACL) strategy that enables you to manage permissions between groups of users.
To access the plugin admin panel, click on the Settings link in the left menu of your Strapi application dashboard and under the USERS & PERMISSIONS PLUGIN section you will find sections for managing Roles, Providers, Email Templates, and Advanced Settings.
When this plugin is installed, it adds an access layer on your application.
The plugin uses JWTs to authenticate users. Your JWT contains your user ID, which is matched to the group your user is in and used to determine whether to allow access to the route.
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.
This is the default role used when the server receives a request without an Authorization header. Any permissions (i.e. accessible endpoints) granted to this role will be accessible by anyone.
It is common practice to select find / findOne endpoints when you want your front-end application to access all the content without requiring user authentication and authorization.
By clicking on the Role name, you can see all functions available in your application (with these functions related to the specific route displayed).
If you check a function name, it makes this route accessible by the current role you are editing. On the right sidebar you can see the URL related to this function.
Submit the user's identifier and password credentials for authentication. On successful authentication the response data will have the user's information along with an authentication token.
The jwt may then be used for making permission-restricted API requests. To make an API request as a user place the JWT into an Authorization header of the GET request.
Any request without a token will assume the public role permissions by default. Modify the permissions of each user's role in the admin dashboard.
Authentication failures return a 401 (unauthorized) error.
jwtSecret: random string used to create new JWTs, typically set using the JWT_SECRETenvironment variable.
jwt.expiresIn: expressed in seconds or a string describing a time span.
Eg: 60, "45m", "10h", "2 days", "7d", "2y". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (minutes, hours, days, years, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").
️❗️ WARNING
Setting JWT expiry for more than 30 days is not recommended due to security concerns.
import axios from'axios';// Request API.// Add your own code here to customize or restrict how the public can register new users.
axios
.post('http://localhost:1337/api/auth/local/register',{
username:'Strapi user',
email:'user@strapi.io',
password:'strapiPassword',}).then(response=>{// Handle success.
console.log('Well done!');
console.log('User profile', response.data.user);
console.log('User token', response.data.jwt);}).catch(error=>{// Handle error.
console.log('An error occurred:', error.response);});
Strapi's backend is located at: strapi.website.com, and
Your app frontend is located at: website.com
The user goes on your frontend app (https://website.com) and clicks on your button connect with Github.
The frontend redirects the tab to the backend URL: https://strapi.website.com/api/connect/github.
The backend redirects the tab to the GitHub login page where the user logs in.
Once done, Github redirects the tab to the backend URL:https://strapi.website.com/api/connect/github/callback?code=abcdef.
The backend uses the given code to get an access_token from Github that can be used for a period of time to make authorized requests to Github to get the user info.
Then, the backend redirects the tab to the url of your choice with the param access_token (example: http://website.com/connect/github/redirect?access_token=eyfvg).
The frontend (http://website.com/connect/github/redirect) calls the backend with https://strapi.website.com/api/auth/github/callback?access_token=eyfvg that returns the Strapi user profile with its jwt. (Under the hood, the backend asks Github for the user's profile and a match is done on Github user's email address and Strapi user's email address).
The frontend now possesses the user's jwt, which means the user is connected and the frontend can make authenticated requests to the backend!
Before setting up a provider you must specify the absolute url of your backend in server.js.
example -config/server.js
💡 TIP
Later you will give this url to your provider. For development, some providers accept the use of localhost urls but many don't. In this case we recommend to use ngrok(opens new window) (ngrok http 1337) that will make a proxy tunnel from a url it created to your localhost url (ex: url: env('', 'https://5299e8514242.ngrok.io'),).
Instead of a generic explanation we decided to show an example for each provider.
In the following examples, the frontend app will be the react login example app(opens new window).
It (the frontend app) will be running on http://localhost:3000.
Strapi (the backend) will be running on http://localhost:1337.
Github doesn't accept localhost urls.
Use ngrok to serve the backend app.
ngrok http 1337
1
Don't forget to update the server url in the backend config file config/server.js and the server url in your frontend app (environment variable REACT_APP_BACKEND_URL if you use react login example app(opens new window)) with the generated ngrok url.
Facebook doesn't accept localhost urls.
Use ngrok to serve the backend app.
ngrok http 1337
1
Don't forget to update the server url in the backend config file config/server.js and the server url in your frontend app (environment variable REACT_APP_BACKEND_URL if you use react login example app(opens new window)) with the generated ngrok url.
Go to the App clients section in your cognito user pool and create a new client with the name Strapi Auth and set all the parameters and then click on Create app client
You should now have an App client id and by clicking on the button Show Details you will be able to see the App client secret. Do copy those two values App client id and App client secret somewhere for later use when configuring the AWS Cognito provider in Strapi.
Go to the App integration section and click on App client settings
Look for your app client named Strapi Auth and enable Cognito User Pool by checking it in the Enabled Identity Providers section of your newly created App client
Fill in your callback URL and Sign out URL with the value http://localhost:1337/api/connect/cognito/callback or the one provided by your AWS Cognito provider in Strapi
In the Oauth 2.0 section select Authorization code grant and Implicit grant for the Allowed OAuth Flows and select email, openid and profile for the Allowed OAuth Scopes
You can now click on Save changes and if you have already configured your domain name then you should be able to see a link to the Launch Hosted UI. You can click on it in order to display the AWS Cognito login page. In case you haven't yet configured your domain name, use the link Choose domain name at the bottom right of the page in order to configure your domain name. On that page you will have an Amazon Cognito Domain section where a Domain prefix is already setup. Type a domain prefix to use for the sign-up and sign-in pages that are hosted by Amazon Cognito, this domain prefix together with the .auth.YOUR_REGION.amazoncognito.com will be the Host URI (Subdomain) value for your strapi configuration later on.
Fill the information (replace with your own client ID and secret):
Enable: ON
Client ID: fill in the App client id (5bd7a786qdupjmi0b3s10vegdt)
Client Secret: fill in the App client secret (19c5c78dsfsdfssfsdfhpdb4nkpb145vesdfdsfsffgh7vwd6g45jlipbpb)
Host URI (Subdomain): fill in the URL value that you copied earlier (myapp67b50345-67b50b17-local.auth.eu-central-1.amazoncognito.com)
The redirect URL to your front-end app: if you are using strapi react-login https://github.com/strapi/strapi-examples/tree/master/login-react/(opens new window) use http://localhost:3000/connect/cognito/redirect but if you do not yet have a front-end app to test your Cognito configuration you can then use the following URL http://localhost:1337/api/auth/cognito/callback
Twitter doesn't accept localhost urls.
Use ngrok to serve the backend app.
ngrok http 1337
1
Don't forget to update the server url in the backend config file config/server.js and the server url in your frontend app (environment variable REACT_APP_BACKEND_URL if you use react login example app(opens new window)) with the generated ngrok url.
Facebook doesn't accept localhost urls.
Use ngrok to serve the backend app.
ngrok http 1337
1
Don't forget to update the server url in the backend config file config/server.js and the server url in your frontend app (environment variable REACT_APP_BACKEND_URL if you use react login example app(opens new window)) with the generated ngrok url.
CAS(opens new window) is an SSO server that supports many different methods of verifying a users identity,
retrieving attributes out the user and communicating that information to applications via protocols such as SAML, OIDC, and the CAS protocol. Strapi can use a CAS server for authentication if CAS is deployed with support for OIDC.
For example, if running CAS locally with a login URL of: https://localhost:8443/cas/login, the value for the provider subdomain would be localhost:8443/cas.
Subdomain: <Your Auth0 tenant url>, example it is the part in bold in the following url: https://my-tenant.eu.auth0.com/
The redirect URL to your front-end app: http://localhost:3000/connect/auth0
Your configuration is done.
Launch the backend and the react login example app(opens new window), go to http://localhost:3000 and try to connect to the provider your configured. It should work 🎉
Once you have configured strapi and the provider, in your frontend app you have to :
Create a button that links to GET STRAPI_BACKEND_URL/api/connect/${provider} (ex: https://strapi.mywebsite/api/connect/github).
Create a frontend route like FRONTEND_URL/connect/${provider}/redirect that have to handle the access_token param and that have to request STRAPI_BACKEND_URL/auth/${provider}/callback with the access_token param.
The JSON request response will be { "jwt": "...", "user": {...} }.
Now you can make authenticated requests 🎉 More info here: token usage.
✋ Troubleshooting
Error 429: It's most likely because your login flow fell into a loop. To make new requests to the backend, you need to wait a few minutes or restart the backend.
Grant: missing session or misconfigured provider: It may be due to many things.
The redirect url can't be built: Make sure you have set the backend url in config/server.js: Setting up the server url
A session/cookie/cache problem: You can try again in a private tab.
The incorrect use of a domain with ngrok: Check your urls and make sure that you use the ngrok url instead of http://localhost:1337. Don't forget to check the backend url set in the example app at src/config.js.
You can't access your admin panel: It's most likely because you built it with the backend url set with a ngrok url and you stopped/restarted ngrok. You need to replace the backend url with the new ngrok url and run yarn build or npm run build again.
Can only be used for users registered using the email provider.
The assumed general flow:
The user goes to your forgotten password page.
The user enters their email address.
Your forgotten password page sends a request to the backend to send an email with the reset password link to the user.
The user receives the email and clicks on the special link.
The link redirects the user to your reset password page.
The user enters their new password.
The reset password page sends a request to the backend with the new password.
If the request contains the code contained in the link at step 3, the password is updated.
The user can log in with the new password.
In the following section we will detail steps 3. and 7..
# Forgotten password: ask for the reset password link
This action sends an email to a user with the link to your reset password page. The link will be enriched with the url param code that is needed for the reset password at step 7.
First, you must specify the following:
In the admin panel: Settings > USERS & PERMISSIONS PLUGIN > Advanced Settings > Reset Password page, the url to your reset password page.
In the admin panel: Settings > USERS & PERMISSIONS PLUGIN > Email Template page, the Shipper email.
Then, your forgotten password page has to make the following request to your backend:
import axios from'axios';// Request API.
axios
.post('http://localhost:1337/api/auth/forgot-password',{
email:'user@strapi.io',// user's email}).then(response=>{
console.log('Your user received an email');}).catch(error=>{
console.log('An error occurred:', error.response);});
This action will update the user password.
This also works with the GraphQL Plugin, with the resetPassword mutation.
Your reset password page has to make the following request to your backend:
import axios from'axios';// Request API.
axios
.post('http://localhost:1337/api/auth/reset-password',{
code:'privateCode',// code contained in the reset link of step 3.
password:'userNewPassword',
passwordConfirmation:'userNewPassword',}).then(response=>{
console.log("Your user's password has been reset.");}).catch(error=>{
console.log('An error occurred:', error.response);});
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Congrats, you're done!
You can also update an authenticated user password through the /change-password API endpoint:
In production, make sure the url config property is set. Otherwise the validation link will redirect to localhost. More info on the config here.
After registering, 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 their registration.
Example of the confirmation link:https://yourwebsite.com/api/auth/email-confirmation?confirmation=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaWF0IjoxNTk0OTgxMTE3LCJleHAiOjE1OTc1NzMxMTd9.0WeB-mvuguMyr4eY8CypTZDkunR--vZYzZH6h6sChFg
If needed you can re-send the confirmation email by making the following request:
import axios from'axios';// Request API.
axios
.post(`http://localhost:1337/api/auth/send-email-confirmation`,{
email:'user@strapi.io',// user's email}).then(response=>{
console.log('Your user received an email');}).catch(error=>{
console.error('An error occurred:', error.response);});
By default this plugin comes with two templates: reset password and email address confirmation. 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.
JWTs can be verified and trusted because the information is digitally signed. To sign a token a secret is required. By default Strapi generates and stores it 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.