Search code examples
node.jsexpressauthenticationauth0

Auth0 + JWT + NodeJS + Express End-user authentication (Login)


Has been almost a year that I switch to Auth0 in order to manage my customer's access to the dashboard of my application. Nowadays I need to implement access for a RESTFULL API.

If I follow the instructions in order to secure the NodeJS app using JWT it works like a charm. The issue is that I am not properly sure on the implementation for the end user in order to get the token needed for access this API.

I thought of creating the tokens on the dashboard or just use a server side implementation for the login/authentication. I did the last using the access to my own database before and worker amazingly. My issue is that I am not completely sure on how to do it for the end user using Auth0.

Anyone implemented a RESTfull API that has login using Auth0 before in order to get the JWT token ? Would my great to hear your thoughts.


Solution

  • The solution was to use a different approach.

    There is an Auth0 endpoint that uses the user and password for the user in order to login with the service. This way I can get the id of the authenticated user and a JWT token that I can use to validate future requests.

    https://auth0.com/docs/api/authentication#resource-owner-password

    This flow should only be used from highly trusted applications that cannot do redirects. If you can use redirect-based flows from your apps we recommend using the Authorization Code Grant instead.

    router.post('/login', function (req, res, next) {
      var options = {
        method: 'POST',
        url: process.env.AUTH0_URL_OAUTH,
        headers: {
          'Cache-Control': 'no-cache',
          'Content-Type': 'application/json'
        },
        body: {
          grant_type: 'password',
          username: req.body.username,
          password: req.body.password,
          audience: process.env.AUTH0_AUDIENCE,
          scope: process.env.AUTH0_SCOPE,
          client_id: process.env.AUTH0_CLIENT_ID,
          client_secret: process.env.AUTH0_CLIENT_SECRET
        },
        json: true
      };
    
      request(options, function (error, response, body) {
        if (error) {
          res.sendStatus(500); //We could not connect to the service
        } else {
          if (body.error) {
            console.log(body);
            res.status(400);
            res.send({
              error: body.error_description // There was an error with the user or password
            });
          } else {
            console.log(body);
            /**
             * Everything went well. We return the JWT
             */
            res.send({
              access_token: body.access_token,
              expires_in: body.expires_in,
              token_type: body.token_type
            });
          }
        };