Search code examples
reactjslumenauth0

Auth0 with ReactJS and Lumen - Audience looks like a random string


I'm currently developing an application that has a ReactJS frontend and a Lumen backend. I'm trying to use Auth0 to make the API accessible only by specific users.

Currently, I have JWT auth setup in Lumen. Using postman, I'm able to make requests for data successfully when setting the test bearer token provided by Auth0.

Here are the settings I'm using for the JWT verification:

$verifier = new JWTVerifier([
    'supported_algs' => ['RS256'],
    'valid_audiences' => ['http://example.com'],
    'authorized_iss' => ['https://example.eu.auth0.com/'],
]);

I have started with ReactJS and so far I'm able to login with Auth0 perfectly fine. Below are the settings for the auth0 connection:

auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.callbackUrl,
    responseType: 'token id_token',
    scope: 'openid profile'
  });

What's returned on successful log in is the access_token and id_token.

Now comes the frustrating part.. I do a GET request for data from my API like so:

axios({
      url:'http://example.com/public/api/enquiries',
      headers: {
        'Content-Type': 'application/json',
        'Authorization':'Bearer ' + localStorage.getItem('id_token'),
      }
    }).then(function(response) {
      console.log(response);
    });

This then returns the following error from my Lumen API:

Invalid audience Wo6olMsBdA0U0azY4q09iZ7bjXPbYSvd; expected http://example.com

I did a var_vump of the decoded data in Lumen and all data is correct EXCEPT the 'aud' item which appears as: Wo6olMsBdA0U0azY4q09iZ7bjXPbYSvd.

I added the above string as an accepted audience and the request is then made successfully but this is surely not correct. Can anyone point me in the right direction?

Much appreciated.


Solution

  • Found the problem.

    So when the data was returned for access_token and id_token, the access_token looked too small to be used for JWT and so I assumed therefore that the id_token was the correct bearer to use. However, what I was missing in my React project when initiating auth0 was the "audience" option and so the access_token was not JWT ready. Adding this gave me a longer access_token that was JWT ready. Parsing that to my API as the bearer worked as it should have done.

    The initiation code for auth0 in react should have been:

    auth0 = new auth0.WebAuth({
        domain: AUTH_CONFIG.domain,
        clientID: AUTH_CONFIG.clientId,
        redirectUri: AUTH_CONFIG.callbackUrl,
        responseType: 'token id_token',
        scope: 'openid profile',
        audience: 'http://example.com'
      });
    

    ..for anyone that comes across this same problem.