express
So what do I do with Token?
mooonQ
2020. 5. 19. 14:30
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
});
};