배운 것들
- access token
- refresh token
- jwt
더 알아볼 것
- Jwt 정리하기
서버에서는 유저가 민감하거나 제한된 정보를 요청할 때마다 유저를 확인하기 위해 가지고 있는 세션 값을 확인하는데 매 요청마다 데이터베이스를 확인해야 하는 번거로움이 생긴다. 이러한 문제를 해결하기 위해 토큰 인증방식을 사용하기 시작했다.
대표적인 토큰 인증방식인 jwt를 사용하는데 이때 주어지는 암호화된 토큰을 클라이언트에 저장하여 인증하는 방식이다. token스프린트를 통해 더 자세하게 토큰 인증방식에 대하여 알게 되었다.
module.exports = async (req, res) => {
const userInfo = await Users.findOne({where: {userId: req.body.userId,password: req.body.password}
})
if (!userInfo) {
res.status(400).json({"data": null,"message": "not authorized"})
} else {
delete userInfo.dataValues.password;
const access_token = jwt.sign(userInfo.dataValues, process.env.ACCESS_SECRET,{expiresIn: "5h"});
const refresh_token = jwt.sign(userInfo.dataValues, process.env.REFRESH_SECRET);
res.cookie('refreshToken', refresh_token, {domain: 'localhost',path: '/',secure: true,httpOnly: true,sameSite: 'none'})
res.status(200).json({"data": {"accessToken": access_token},"message": "ok"})
}
};
로그인 요청 시 secret과 같은 salt를 사용하여 jwt.sign을 통해 토큰을 발행하고 client에 넘겨준다. 이는 state와 같은 곳에 저장해 두었다가 정보를 요청할 시 토큰을 함께 보내준다.
module.exports = async (req, res) => {
if(!req.headers['authorization']){
res.status(400).json({ "data": null, "message": "invalid access token" })
}
else{
const authorization = req.headers['authorization'];
const token = authorization.split(' ')[1];
const data = jwt.verify(token, process.env.ACCESS_SECRET)
const userInfo = await Users.findOne({where:{userId:data.userId}})
if(!userInfo){
res.status(400).json({ "data": null, "message": "access token has been tempered" }
)
} else{
console.log(userInfo)
delete userInfo.dataValues.password
res.status(200).json({ "data": {userInfo}, "message": "ok" }
)
}
}
};
이처럼 요청을 받으면 headers의 토큰을 확인하고 원하는 정보를 보내준다.
'TIL' 카테고리의 다른 글
20210317 first project #1 (2) | 2021.03.18 |
---|---|
20210308 TIL (0) | 2021.03.08 |
20210304 TIL (0) | 2021.03.04 |
20210303 TIL (0) | 2021.03.03 |
20210302 TIL (0) | 2021.03.02 |
댓글