Nest: Question: get JWT logged user

Created on 10 Apr 2018  路  5Comments  路  Source: nestjs/nest

Hello,

I'm using graphql + jwt authentication and I have small problem.
I don't know how can I get records from database for logged user (where user_id = logged_user_id).
How can I get user_id in service classes?

Thank you for your answer.

question 馃檶

Most helpful comment

I have the solution, for me was a problem with de jwt library. You should encode your user information in the login method if you want to get the user information in other requests. I have this code for the login method:

genToken(userLogged) {
      const token = {
      token: jwt.sign({
        user: userLogged,
        exp: Math.round(new Date().getTime() / 1000) + 604800},
      'my-secret-string')}
      return token;
  }

In this method, I pass the complete user object that I get from the database. To check that you're enconding correctly the information, paste your generated token in this website: https://www.jsonwebtoken.io/.

To get the user id in another request you can put in your controller method, in the first param a Request object:

@Get('/posts')
  getPosts(@Req() request, @Response() res) {
      this.usersService.getUserPosts(request.payload.user.id).then(posts => {
      res.status(HttpStatus.OK).json(articles);
    });
  }

And I hace this code in my middleware:

if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            const token = req.headers.authorization.split(' ')[1];
            jwt.verify(token, 'my-secret-string', (err, payload) => {
              if (!err) {
                // confirm identity and check user permissions
                req.payload = payload;
                next();
              } else {
                 return res.status(403).json(err);
              }
            });
          } else {
            return res.status(401).json('The access token is not valid.');
          }

All 5 comments

I have the same question, so if someone knows the answer I need a solution too!

As shown here: https://docs.nestjs.com/graphql/quick-start, request is passed as a root value. In queries, first passed argument (obj) is equal to request, while in resolvers you have an access to the root value (request) through info parameter. Your JWT is probably sent over the network using headers, therefore you can easily grab its value directly from the request instance. More details: https://www.apollographql.com/docs/graphql-tools/resolvers.html

Another approach is to use context. You can pass a request as a context value in the graphqlExpress() function, then, access this object inside your queries/mutations/resolvers.

I have the solution, for me was a problem with de jwt library. You should encode your user information in the login method if you want to get the user information in other requests. I have this code for the login method:

genToken(userLogged) {
      const token = {
      token: jwt.sign({
        user: userLogged,
        exp: Math.round(new Date().getTime() / 1000) + 604800},
      'my-secret-string')}
      return token;
  }

In this method, I pass the complete user object that I get from the database. To check that you're enconding correctly the information, paste your generated token in this website: https://www.jsonwebtoken.io/.

To get the user id in another request you can put in your controller method, in the first param a Request object:

@Get('/posts')
  getPosts(@Req() request, @Response() res) {
      this.usersService.getUserPosts(request.payload.user.id).then(posts => {
      res.status(HttpStatus.OK).json(articles);
    });
  }

And I hace this code in my middleware:

if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            const token = req.headers.authorization.split(' ')[1];
            jwt.verify(token, 'my-secret-string', (err, payload) => {
              if (!err) {
                // confirm identity and check user permissions
                req.payload = payload;
                next();
              } else {
                 return res.status(403).json(err);
              }
            });
          } else {
            return res.status(401).json('The access token is not valid.');
          }

try this code ....
if (account) {

res.json({ account, token: jwt.sign({ user: account._id }, 'test', { expiresIn: '100d' }) });

}

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

breitsmiley picture breitsmiley  路  3Comments

tronginc picture tronginc  路  3Comments

marshall007 picture marshall007  路  3Comments

VRspace4 picture VRspace4  路  3Comments

janckerchen picture janckerchen  路  3Comments