Search code examples
openid-connectopenid

How to verify and use access token to access an API resource?


Hey I am using open id connect authorization code flow to authenticate my user. After successful authentication I receive a access token and ID token. Now, I am confused once my user is authenticated from OIDC provider access and ID token is granted, so now to access APIs of my application I will pass access token as bearer token in each API request and how my app will then verify that access token is still valid and have access of the requested API? Do I need to make an request to OIDC provider again to verify the access token validity? if yes then is not a overhead that for each API I have to send an request to OIDC provider to verify my access token and to check that user has access to this API or not ? Please suggest me the best way to authenticate the user for API access that does not cost much


Solution

  • APIs validate a JWT access token on every request, using a security library. The first of these will download token signing public keys from an Authorization Server's JWKS endpoint - and the library should then cache these for you.

    Here is some example code in Node.js, and the same type of code can be written in any programming language. You will need to inspect your JWT access token, eg in OAuth Tools, to view the issuer and audience claims it contains, then configure them.

    const accessToken = readAccessTokenFromAuthorizationHeader();
                
    const remoteJwkSet = createRemoteJWKSet(new URL(this._configuration.jwksEndpoint));
    const options = {
        algorithms: ['RS256'],
        issuer: 'myissuer',
        audience: 'myaudience',
    };
    
    // Verify the JWT's digital signature
    const result = await jwtVerify(accessToken, remoteJwkSet, options);
    
    // On success, you can then use claims to enforce authorization
    const claims = result.payload;