-
Middleware and Decode(token)Javascript/Node.js and Express 2021. 7. 15. 17:42
app.js
//토큰확인 router.get('/auth', authMiddleware, async (req, res) => { const user = res.locals.user; res.send({ loginid: user.loginid }) });
authMiddleware.js
const jwt = require("jsonwebtoken"); const User = require("../models/user"); module.exports = async(req, res, next) => { const { authorization } = req.headers; const [tokenType, tokenValue] = authorization.split(" "); if(tokenType !== 'Bearer'){ res.status(401).send({ errorMessage: '로그인 후 사용하세요' }); return; }; try { const { loginid } = jwt.verify(tokenValue, "ThisIsSecretKey") const foundUser = await User.findOne({loginid}) res.locals.user = foundUser; next(); } catch (error) { res.status(401).send({ errorMessage: '로그인 후 사용하세요' }); return; } };
'Javascript > Node.js and Express' 카테고리의 다른 글
AWS 배포 및 몽고db연결 (0) 2021.07.22 Javascript and Crawling (Axios, Cheerio, IconV-Lite) (0) 2021.07.15 Register and Joi(Validation) (0) 2021.07.15 Login, Token(JWT) and Authentication (0) 2021.07.15 imageUpload and Multer(Javascript, Node.js) (0) 2021.07.15