-
Login, Token(JWT) and AuthenticationJavascript/Node.js and Express 2021. 7. 15. 17:41
app.js
const jwt = require("jsonwebtoken"); const secretKey = 'ThisIsSecretKey'; const User = require("../models/user"); //로그인 router.post('/login', async (req, res) => { const { loginid, password } = req.body; const user = await User.findOne({ $and : [{ loginid: loginid}, {password : password }] }) if (!user) { res.status(401).send({ errorMessage: '로그인에 실패했습니다. ' }); return; } const token = jwt.sign( { loginid: user.loginid, username: user.username }, secretKey ); res.send({ token }); }) //토큰확인 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' 카테고리의 다른 글
Middleware and Decode(token) (0) 2021.07.15 Register and Joi(Validation) (0) 2021.07.15 imageUpload and Multer(Javascript, Node.js) (0) 2021.07.15 EC2, S3 and CORS (0) 2021.07.15 Node.JS, Express and Javascript (0) 2021.07.15