본문 바로가기

express

So what do I do with Token?

When I use token?

Usually when users login. If user logins with collect data and process, Server sends Token. Token is contained in response object.

 

Before send Token, we need to issue token.

How we issue JWT?  Easy. Use 'jwt.sign() method'

jwt.sign(payload, secret, option, [callback])

payload: datas token will contains

secret: secret key will be used for hashing algorithm

options: token options like expiresIn, issuer etc.

 

We can define methods issuing token in our model.

// app/models/User.js
UserSchema.methods.getSignedJwtToken = function() {
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRE
  });
};

After make method which can issue token, just issue token and send to the user.

// app/controllers/auth.js
exports.login = asyncHandler(async (req, res, next) => {
  const { email, password } = req.body;
  
  // Validate inputs
  ~~
  
  // If all input is valid
  const user = await User.findOne({ email });
  
  sendTokenResponse(user, 200, res);
});


const sendTokenResponse = (user, statusCode, res) => {
  // create token
  const token = user.getSignedJwtToken();
  
  const options = {
    expires: new Date(
      Date.now() + process.env.JWT_COOKIE_EXPIRE * 24* 60* 60* 1000
    ),
    httpOnly: true
  };
  
  res
    .status(statusCode)
    .cookie('token', token, options)
    .json({
      success: true,
      token
    });
};

By storing token in Browser cookie, User can have access.

'express' 카테고리의 다른 글

When we forgot password/ using registered email. [Express, Node]  (0) 2020.05.21
Query mongoose  (0) 2020.05.21
TOKEN authentication  (0) 2020.05.19
What should I do with Errors? express.js  (0) 2020.05.17
Error Handling using Promise.  (0) 2020.05.16