Store tokens, validate access tokens, refresh sessions, and handle sign-out.
Successful authentication responses include both an access token and a refresh token. Store the access token as a secure cookie in the user’s browser and validate it on each backend request. Store the refresh token either in a secure cookie or persisted on your backend. Once the access token has expired, obtain a new one using the refresh token.
If you’re using the Next SDK or Remix SDK, token validation and refresh handling is automatic. Read on for details about how token handling works under the hood.
Validate the access token on each request using a JWT library like jose. The signing JWKS can be found at http://api.workos.com/sso/jwks/<clientId>. The JWT includes the following claims:
sub: the WorkOS user IDsid: the session ID (used for signing out)iss: https://api.workos.com/ (or your custom auth domain if configured)org_id: the organization selected at sign-in time (if applicable)role: the role of the selected organization membership (only applicable if an organization is selected)permissions: the permissions assigned to the role (if applicable)exp: the standard expires_at claim (the token should not be trusted after this time)iat: the standard issued_at claimPersist refresh tokens on the backend in a database, cache, or secure HTTP-only cookie. Obtain a new access token by using the authenticate with refresh token endpoint. If the session is still active, a new access token and refresh token are returned. Refresh tokens may be rotated after use, so replace the old refresh token with the newly returned one.
Use refresh tokens to obtain a new access token for a different organization by passing the organization_id parameter to the authenticate with refresh token endpoint. If the session for the refresh token is authorized to access the organization, then the org_id will be set to the given organization, along with the role and permissions claims matching the user’s membership in that organization.
If the user is not authorized for the organization, an appropriate authentication error is returned and the user needs to authenticate. Use the Get Authorization URL with the organization_id parameter to initiate the authentication flow specifically for the organization.
When a user signs out, follow these steps:
sid claim) from the access token.
// extract sessionId from access token const sessionId = jose.decodeJwt(session.accessToken).sid; // delete app session cookie cookies().delete('my-app-session'); // redirect to logout endpoint // (the user will be redirected to your sign-out redirect // after the logout completes) redirect(workos.userManagement.getLogoutUrl({ sessionId }));