#6-0 ๋ค์ด๊ฐ๋ ๋ง
์ด์ ์ ํฌ์คํ
ํ๋๋๋ก(https://white-salt.tistory.com/26) JWT ๋ฐฉ์์ผ๋ก ๋ก๊ทธ์ธ ๊ธฐ๋ฅ์ ๊ตฌํํด๋ณด์๋ค. jwt ๊ฐ๋
์ ์ดํดํ๋ ๊ฒ๋ ์กฐ๊ธ ์ด๋ ค์ ๋๋ฐ ์ค์ ๋ก ์ฝ๋ ์ง๋๊ฑด ๋ ์ด๋ ค์ ๋ค (^_^;;). ์ผ๋จ ์ง๊ธ๊น์ง ์ง ์ฝ๋๋ฅผ ํ๋ฒ ์ ๋ฆฌ ํ ๋ฐฑ์๋ ์น๊ตฌ์ ํ์๋ฅผ ์งํํด๋ณด์.
#6-1 ๋ก๊ทธ์ธ ๊ธฐ๋ฅ ๋ก์ง
1. ์์ด๋์ ํจ์ค์๋๋ฅผ ์๋ฒ๋ก ์ ์กํ์ฌ accessToken๊ณผ refreshToken ๋ฐ๊ธฐ.
์ ๋ ฅ๋ฐ์ id์ password ๊ฐ์ ์๋ฒ๋ก ๋ณด๋ด๋ฉด, ์๋ฒ๋ ์ ์ ํ์ธ ํ ๋ฑ๋ก๋ ์ ์ ๊ฐ ๋ง๋ค๋ฉด accessToken, refreshToken์ ๋ฐ๊ธํด์ค๋ค.
(Q1. ์ด๋ ๋ฐ๊ธ ๋ฐ์ refreshToken์ httpOnly cookie๋ก ์๋ฒ๋จ์์ ๋ฐ๋ก ์ ์ฅํด์ฃผ๊ณ , ์ดํ ํด๋ผ์ด์ธํธ์์ cookie์ ์ ์ฅ๋ refreshToken์ ํ์ํ ๋ ๊ฐ์ ธ๋ค ์ฐ๋ฉด ๋๋๊ฑด๊ฐ?)
2. ์ดํ accessToken์ ๋งค Api ํธ์ถ๋ง๋ค ํค๋์ ๋ถ์ฌ์ ์ ์กํ๊ณ , ์๋ฒ๋ accessToken์ ๊ฒ์ฆํ ํ ๋ค์ accessToken๊ณผrefreshToken์ ๋ฐ๊ธํด์ค๋ค.
*HTTP ํค๋๋ ํด๋ผ์ด์ธํธ์ ์๋ฒ๊ฐ ์์ฒญ ๋๋ ์๋ต์ผ๋ก ๋ถ๊ฐ์ ์ธ ์ ๋ณด๋ฅผ ์ ์กํ ์ ์๋๋ก ํด์ค๋ค.
(Q2. ๋งค๋ฒ accessToken ๊ฒ์ฆ ํ ๋ฐ์ ๋ ํ ํฐ์ ๊ธฐ์กด๊ณผ ๋๋ค๋ฅธ ์๋ก์ด ํ ํฐ์ธ์ง? ์๋ accessToken์ด ์ผ์นํ๋ค๋ status ๊ฐ๋ง ์ ์กํด์ฃผ๋์ง?)
// LoginPresenter.js
const handleSubmit = (e) => {
e.preventDefault();
const id = idData.current.value;
const password = passwordData.current.value;
props.onlogin(id, password);
}
// LoginController.js
const onlogin = (id, password) => {
const data = {id, password};
const headers = {
'Content-Type': 'application/json'
};
axios.post("/login", data, {headers: headers})
.then((res)=> {
const {accessToken} = res.data;
dispatch({type: 'LOGIN_SUCCESS', payload: {"accessToken": accessToken}});
// API ์์ฒญํ๋ ์ฝ๋ง๋ค ํค๋์ accessToken ๋ด์ ๋ณด๋ด๋๋ก ์ค์
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
history.push("/");
})
.catch((error)=>{
dispatch({type: 'LOGIN_FAILURE'});
// refreshTokenSaveCookie(id);
history.push("/login");
console.log('LOGIN FAILURE');
})
}
3. ๋ง์ฝ accessToken์ด ๋ง๋ฃ๋์์ผ๋ฉด refreshTokenRequest ํจ์๊ฐ ์คํ๋์ด ์ฟ ํค์ ์ ์ฅ๋ refreshToken์ ์๋ฒ์ ๋ณด๋ด ๋ค์ ์๋ก์ด accessToken์ ๋ฐ๊ธ ๋ฐ๋๋ค.
์๋ก์ด accessToken์ ๋ค์ ๋งค Api ํธ์ถ๋ง๋ค ํค๋์ ๋ถ์ฌ์ ์ ์กํ๋ค.
(**accessToken์ด ๋ง๋ฃ๋์ด ์๋ฒ์์ 400 ์๋ฌ๋ฅผ ๋ณด๋ด์ฃผ๋ฉด ์ด๋ฅผ ๊ฐ์ง ํ refreshTokenRequest ํจ์๊ฐ ์คํ๋๋๋ก ์ฝ๋๋ณด์ ํ์ํจ)
(Q3. ์ด๋ refreshToken๋ ์๋ก์ด ๊ฐ์ด๊ณ ๋ฐ๋ก ๋ ์๋ฒ๋จ์์ ์ฟ ํค์ ์ ์ฅํด์ฃผ๋?)
// auth.js
export const refreshTokenRequest = () => {
const refreshToken = Cookie.get("refreshToken");
const data = {
refreshToken
};
const headers = {
'Content-Type': 'application/json'
};
axios.post('/token/refresh', data , {headers: headers})
.then((res)=>{
const { accessToken } = res.data;
// accessToken ์ค์
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
})
.catch(error => {
console.log('refreshToken error')
});
}
'[PROJECT] ๋ด์ผ์ ์ง' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
#7. ํ์๊ฐ์ ์ ํจ์ฑ ๊ฒ์ฌ (react-hook-form) (0) | 2021.10.17 |
---|---|
#5. ์ฝ๊ด๋์ ์ฒดํฌ๋ฐ์ค ๊ธฐ๋ฅ ๊ตฌํ (2) | 2021.09.27 |
#4. ์บ๋ก์ (Carousel) ๊ตฌํํ๊ธฐ (0) | 2021.09.25 |
#3. ๋ชจ๋ฌ์ฐฝ ๊ตฌํ( feat. ์์ญ ๋ฐ ํด๋ฆญ ์ ๋ซ๊ธฐ) (0) | 2021.09.15 |
#2. ๋ก๊ทธ์ธ ๊ธฐ๋ฅ ๊ฐ๋ ์ก๊ธฐ (0) | 2021.09.13 |