Api authentication with credentials from a react-native app

Hi there,

I have a react-native app and I’m using the react-native-auth0 SDK to login a user and get credentials when the login is successful.

const onLogin = async (callback) => {
    try {
      await authorize().then(async () =>{
        const credentials = await getCredentials();
        await AsyncStorage.setItem('token', credentials.idToken);
        if (callback) {
            callback(); // Call the callback function if provided
          }
      });
    } catch (e) {
      console.log(e);
    }
  };

How I expect to use that token is adding it as an auth bearer to all requests to the API, and verifying the token in a NodeJS backend using the library jsonwebtoken.

module.exports = function(req, res, next) {
    const token = req.header("authorization").replace('Bearer ','');
    if (!token) return res.status(401).json({ message: "Auth Error" });
  
    try {
      var cert = fs.readFileSync(path.resolve(__dirname, '.public key'));  // get public key
      const decoded = jwt.verify(token, cert);
      req.user = decoded.user;
      next();
    } catch (e) {
      console.error(e);
      res.status(500).send({ message: "Invalid Token" });
    }
  };

If I use the idToken the JWT verification works as expected and I can decode the JWT and access user info. The reason why I’m not sure if my approach is correct is because this page says that you should never use Id tokens to obtain direct access to APIs, however, if I use credentials.accessToken the verification fails with a “malformed JWT error”.

Any guidance on the topic is appreciated.

Cheers,

Hey there @davitoc welcome to the community!

That’s correct, you shouldn’t use an ID token against an API but rather an access token - Are you passing an audience param anywhere when initiating WebAuth?

Let us know!

Hi Tyf,

Thanks for bringing that up. I wasn’t passing an audience param when initiating WebAuth.

I have done so now in addition to follow up a guide for the Mobile + API implementation.

  const onLogin = async (callback) => {
    const authorizeConfig ={
      issuer: 'API issuer,
      audience:'API audience'
    };

    try {
      await authorize(authorizeConfig).then(async () =>{
        const credentials = await getCredentials();

        await AsyncStorage.setItem('token', credentials.accessToken);
        if (callback) {
            callback(); // Call the callback function if provided
          }
      });
    } catch (e) {
      console.log(e);
    }
  };

Got it working :raised_hands:

1 Like

Hey @davitoc that’s great news thanks for sharing here! :rocket:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.