Using bearer tokens

Sending session ids as bearer tokens is useful when your frontend and backend is hosted on a different domain, such as certain single page applications, mobile apps, and desktop apps. Bearer tokens are sent in the authorization header, prefixed with Bearer.

Authorization: Bearer <session_id>

Some methods shown in this page is included in AuthRequest, which is described in Handle requests page.

Validate bearer tokens#

You can use AuthRequest.validateBearerToken() to validate the bearer token. Since Auth.validateSession() is used, idle sessions will be reset. It returns the validated session or null if the session is invalid.

const authRequest = auth.handleRequest();

const session = await authRequest.validateBearerToken();
if (session) {
	// valid request
}

CSRF protection is not included when validating bearer tokens.

Read bearer tokens#

You can get the session id from the authorization header using Auth.readBearerToken(), which returns a session id or null if the token does not exist. This does not validate the session id.

const authorizationHeader = request.headers.get("Authorization");
const sessionId = auth.readBearerToken(authorizationHeader);

Caching#

AuthRequest.validateBearerToken() caches the request, so it will only run once no matter how many times you call it. This is useful when you have multiple pages/components the method can be called.

await authRequest.validateBearerToken();
await authRequest.validateBearerToken(); // uses cache from previous call
await Promise([
	authRequest.validateBearerToken(),
	authRequest.validateBearerToken() // waits for first call to resolve
]);

Invalidation#

After updating user attributes, for example, call AuthRequest.invalidate() to invalidate internal cache so the next time you call AuthRequest.validateBearerToken(), it returns the latest user data.

await auth.updateUserAttributes(userId, {
	username: newUsername
});
authRequest.invalidate();

// returns latest user data
const session = await authRequest.validateBearerToken();