Most apps are going to need to identify a user so that the user has access to their own stuff but not others. E.g. a blogging platform which allows users to edit their own posts but not others. How do i get my user from the auth0 token?
I understand the general approach, but a tutorial or github repo with both the SPA side and the API side would be really helpful, e.g. how do i send my auth0_id (or similar) with my request so that i can use that to determine user on the API side.
ID Token - This token is used by the SPA to get basic profile information. It is received as a JWT and conveniently decoded by whichever Auth0 SDK you are using. For example with auth0-spa-js:
document.getElementById('login').addEventListener('click', () => {
auth0.loginWithRedirect({
redirect_uri: 'http://localhost:3000/'
}).then(token => {
//logged in. you can get the user profile like this:
auth0.getUser().then(user => {
console.log(user);
});
});
});
Access Token - The SPA will pass this token in its Authorization header as a bearer token in API requests:
Since it sounds like you may be calling your own API, you will need to register your API with Auth0 and use the API identifier as the audience when you initiate the Auth0 client:
import createAuth0Client from '@auth0/auth0-spa-js';
// either with async/await
const auth0 = await createAuth0Client({
domain: 'YOUR_DOMAIN',
client_id: 'YOUR_CLIENT_ID',
audience: 'YOUR_API_IDENTIFIER'
});
For a more comprehensive walkthrough, I’d recommend taking a look at the Auth0 blog for articles such as:
is the access token a JWT also? do I include the identifying info there (e.g. auth0_id)? if so how?
and then I assume I decode the token on the API server call to get the id? If you have a Rails snippet (or some other server-side code) on how to do this, would be helpful
The Access Token will be a JWT if you provide an audience in the authorization request. For example:
const auth0 = await createAuth0Client({
domain: 'YOUR_DOMAIN',
client_id: 'YOUR_CLIENT_ID',
audience: 'YOUR_API_IDENTIFIER' // <-- use your API identifier as the audience
});
Otherwise, it will be an opaque token that can’t be decoded, but can be used for calling the https://your-domain/userinfo endpoint.
When you provide an audience in your SPA application and receive a JWT for the Access Token, the sub claim of the decoded token will be the user ID within Auth0. You can use this to retrieve additional information about the user.