Search code examples
javascriptjwtoktaokta-api

Jwt cannot be parsed, Okta


I am trying to set up Okta authentication on my React App. On the client side I am able to authenticate successfully and I get the access token. However when I try to authenticate a backend service using OktaJwtVerfier, I get the error message: 'Jwt cannot be parsed. SyntaxError: Unexpected token in JSON at position 0'

I have develop a very simple test program to test the verification of the token, so basically I get authenticated on the browser, I copy paste the jwt token in my small script to test authentication, and it fails with the message above, what am I doing wrong?

const OktaJwtVerifier = require('@okta/jwt-verifier');


const oktaJwtVerifier = new OktaJwtVerifier({
    issuer: "https://dev-XXXXX.oktapreview.com/oauth2/default",
    clientId: "XXXXXX",
    assertClaims: {
        'aud': 'api://default',
        'cid': "XXXXXX",
    },
});


const accessToken = 'Bearer eyJraWQiO.....';


oktaJwtVerifier.verifyAccessToken(accessToken).then((jwt) => {
    console.log('auth succesfulll', jwt);
}).catch((e)=> {
    console.log(e);
})

Solution

  • The comment by @jps is correct. Your header has a value of Bearer XXXX, where XXXX is the actual JWT string to parse.

    Here's an example from the Okta project of how they do it in an Express app:

    const authHeader = req.headers.authorization || '';
    const match = authHeader.match(/Bearer (.+)/);
    if (!match) {
      res.status(401);
      return next('Unauthorized');
    }
    
    const accessToken = match[1];
    

    You can see the code in its full context here.

    your code could be modified as follows:

    const headerValue = 'Bearer eyJraWQiO.....';
    
    const match = headerValue.match(/Bearer (.+)/);
    if (!match) {
      throw new Error('your error message here')
    }
    
    const accessToken = match[1];
    
    oktaJwtVerifier.verifyAccessToken(accessToken).then((jwt) => {
      console.log('auth succesfulll', jwt);
    }).catch((e)=> {
      console.log(e);
    })