DEV Community

jgngo
jgngo

Posted on • Updated on

Strapi Authentication via Provider

If you use a 3rd party provider in Strapi for authentication, the access token works a little differently.

The access token that you receive from cognito is not valid in Strapi. You need to retrieve a token from strapi.

From the frontend app, read the query string from cognito after successful authentication and submit both the id_token and access_token to this Strapi endpoint.

If you are using the AWS Amplify SDK, Auth.currentSession() will return a CognitoUserSession containing the accessToken and idToken.

const data = await Auth.currentSession()
const access_token = data.accessToken.jwtToken
const id_token = data.idToken.jwtToken
Enter fullscreen mode Exit fullscreen mode

Send both Cognito tokens to the callback URL so that you can get a Strapi JWT that you can then use for all subsequent calls to Strapi. By calling this URL, Strapi will automatically create a new record in the User table.

${backendUrl}/api/auth/${params.providerName}/callback?id_token=xxx&access_token=yyy

You will receive the following response.

{
"jwt": "<access token> that you can use thereafter",
"user": {
  "id": 1,
  "username": "google_999999999999999999",
  "email": "theuser@gmail.com",
  "provider": "cognito",
  "confirmed": true,
  "blocked": false,
  "createdAt": "2022-05-30T02:50:08.907Z",
  "updatedAt": "2022-05-30T02:50:08.907Z"
}
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
oscar_jacome_e5fdb1d77dec profile image
Oscar Jacome

I've been trying to set-up cognito as an Auth provider for my app without luck.
Thank you sir, this was of great help.
Question, how do I populate the name for my user in Strapi? At the moment this is blank

Collapse
 
juliosmorelos profile image
Jules

By calling ${backendUrl}/api/auth/${params.providerName}/callback?id_token=xxx&access_token=yyy i receive an error 400.

So I guess I am having an error in the strapi provider configuration. Could you give more info about it?