Introduction
JWT 에 대해서 알아보고, JWT 토큰 발급 후 토큰 처리 방법에 대해 알아보려 한다.
JWT란?
JWT는 JSON Web Token의 약자로, 인증에 필요한 정보들을 암호화시킨 JSON 토큰을 의미한다.
서버에서 JWT 토큰의 유효 기간을 설정하고, 클라이언트에서 서버에 데이터 요청할 시 JWT를 HTTP 헤더에 포함하여 서버가 유효 여부를 확인 할 수 있도록 한다.
① 서버에 데이터를 보낸 후 JWT를 response로 받는다.
② JWT 값인 response.data를 로컬 스토리지와 응답 헤더에 넣는다.
async function postInfo(e) {
try {
e.preventDefault();
const response = await axios
.post("http://localhost:8080/login", {
userId: id,
password: password,
}, { "Content-Type": 'application/json', withCredentials: true });
if(response.status === 200){
alert("로그인 성공!");
//response header에 Authorization 값으로 토큰을 넣는다.
axios.defaults.headers.common['Authorization'] = response.data;
//localStorage에 토큰 값 넣는다.
window.localStorage.setItem("token", response.data.slice(7));
}
} catch (error) {
alert(`로그인 실패!
정보를 다시 확인해주세요.`);
}
③ 서버에 데이터 요청 시 JWT 를 HTTP 헤더에 포함하여 서버에 전송한다.
//비밀번호 확인 과정
function chkPw(e) {
console.log(password);
e.preventDefault();
axios.post('http://localhost:8080/api/user/checkPassword', {
password: password,
}, { headers: {Authorization: `Bearer ${window.localStorage.getItem('token')}` } }
)
.then((res) => {
if (res.data === 1) {
alert('비밀번호가 일치합니다.');
navigate('/chnInfo');
}
else {
alert('비밀번호가 일치하지 않습니다. 다시 입력해주세요.')
}
})
.catch((error) => {
console.log(error);
})
'Frontend > ReactJS' 카테고리의 다른 글
[React] ReactPortal 이용하여 modal 창 생성 (0) | 2023.02.19 |
---|---|
[React] useNavigate로 데이터 전달 (0) | 2023.02.16 |
[React] Fetch & Axios (0) | 2023.02.05 |
[React] login 여부 확인 (0) | 2023.02.03 |
[React] 삼항연산자 & map() (0) | 2023.02.02 |