DEV Community

jgngo
jgngo

Posted on • Edited on

6 3 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay