• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

JWT SSR 리프레쉬 토큰처리 감을 전혀 못잡겠습니다.

21.06.18 11:21 작성 조회수 2.61k

1

백엔드와 제로치님의 프론트 소스는 아래와 같습니다. 어떤식으로 처리해야될지 전혀 감을 잡지 못하겠습니다.

export const getServerSideProps = wrapper.getServerSideProps(async (context) => {
console.log(context.req.headers);
const cookie = context.req ? context.req.headers.cookie : '';
axios.defaults.headers.Cookie = '';
axios.defaults.headers.common.Authorization = '';
if (context.req && cookie) {
//axios.defaults.headers.Cookie = `Bearer ${cookie}`;
axios.defaults.headers.Cookie = cookie;
axios.defaults.headers.common['Authorization'] = cookie;
}

context.store.dispatch({
type: LOAD_MY_INFO_REQUEST,
});

context.store.dispatch(END);
console.log('getServerSideProps end');
await context.store.sagaTask.toPromise();
});
@Public()
@UseGuards(JwtRefreshGuard)
@Get('refresh')
async refresh(@Req() req, @Res({ passthrough: true }) res: Response) {
// if(req.user){
// const user = req.user;
// const { currentHashedRefreshToken, user_pwd, ...result } = user;
// const {
// accessToken,
// ...accessOption
// } = this.authsService.getCookieWithJwtAccessToken(result.user_id);
// res.cookie('Authentication', accessToken, accessOption);
// return result;
// }else{
// return res.status(200).json(null);
// }

const user = req.user;
const { currentHashedRefreshToken, user_pwd, ...result } = user;
const {
accessToken,
...accessOption
} = this.authsService.getCookieWithJwtAccessToken(result.user_id);
res.cookie('Authentication', accessToken, accessOption);
return result;
}

답변 3

·

답변을 작성해보세요.

0

이재석님의 프로필

이재석

2022.08.10

혹시 문제 해결 하셨을까요??

0

욧닭님의 프로필

욧닭

2021.06.18

작성하신 코드 언어가 어떤언어인지는 잘 모르겠지만.. 로직정도는 알고 있습니다.

보통 실 사용 토큰과 리프레쉬 토큰은 DB에 넣어둡니다.

실 사용토큰은 보통 인증 시간이 짧고(보통 30분 내외) 리프레쉬 토큰은 길어요(보통 1 ~ 2주)

프론트에서 auth를 필요로 하는 행위를 했을때 백에서는 실 사용 토큰을 검증 합니다. 

토큰이 만료 됬거나 변조 되었다면 프론트 에게 리프레쉬 토큰을 요청합니다.

만약 리프레쉬 토큰이 인증이됬으면 실 사용 토큰을 새로 발급해 주고 프론트에서는 발급 받은 토큰으로 다시 auth관련 요청을 하게 됩니다.

! 리프레시 토큰이 만료 됬을때는

로그인을 해서 실 사용 토큰과 리프레쉬 토큰을 다시 발급 받는 방법 밖에 없습니다

만료 기준은 db에 저장되어 잇는 발급 시간으로 비교 하게 됩니다 

도움이 됬으면 좋겠습니다 ^^

네 답변감사합니다.

말씀하신 플로우로 처리한거긴 한건데 getServerSideProps에서 토큰정보가 넘어오지 않아

발생하는 문제입니다.

전체적인 플로우는 말씀하신것처럼 처리한게 맞습니다.. SWR로는 잘넘어오는데

희안하게 ServersideProps에서만 넘어오지 않네요...ㅜㅜ

0

답변감사합니다.

백엔드쪽에서 

아래와 같이 쿠키로 요청하고 프론트에서는 서버사이드 옵션을 써서 getServersideProps를

써서 쿠키를 가져오는건데 이상하게 토큰정보가 사라지네요..

리프레쉬로 요청보내면 Authorization 쿠키를 재발급 받거든요

postman에서는 정상적으로 쿠키가 계속 바뀌는데 브라우저에서는 아예 저 쿠키가 보여지지가

않아서 헤매고 있습니다.ㅜㅜ

res.cookie('Authorization', accessToken, accessOption);
export const getServerSideProps = wrapper.getServerSideProps(async (context) => {
console.log('getServerSidePropsstart');
// console.log(context.req.headers);
context.res.setHeader("set-cookie", "");
const cookie = context.req ? context.req.headers.cookie : '';

//console.log(cookie)

//console.log(cookies.parse(cookie).Authorization);
console.log(axios.defaults.headers.Cookie);
axios.defaults.headers.Cookie = '';
//console.log(axios.defaults.headers.Cookie)
if (context.req && cookie) {
axios.defaults.headers.Cookie = cookie;
cookies.parse(cookie).Authorization = '';
axios.defaults.headers.common['Authorization'] = cookies.parse(cookie).Authorization
axios.defaults.headers.common['Refresh'] = cookies.parse(cookie).Refresh
}

//console.log(axios.defaults.headers.Cookie);
context.store.dispatch({
type: LOAD_MY_INFO_REQUEST,
});
context.store.dispatch(END);
console.log('getServerSideProps end');
await context.store.sagaTask.toPromise();
});

브라우저에 쿠키가 없다는 것인가요? context.res.setHeader로 직접 설정해주세요.

네 그것도 해봤는데...

getServersideProps에 dispatch를 하면

리프레쉬할때 백엔드서버에 호출되는게 아닌가요?

보니까 리프레쉬를해도 서버에 호출이 되지않네요

ㅜㅜ 이유가있을까요?

dispatch 해서 axios request가  실행된다면(주소도 백엔드 주소라면) 백엔드에 요청이 가는게 맞습니다.

답변 감사합니다 희안하게 getServerSideProps로 하게되면 백엔드(nestjs)에서 쿠키로 날려주는

토큰정보가 절대 넘어오지 않아서.. 이유를 알수 없네요 그래서 SWR로 먼저 요청하는 식으로 변경했습니다....ㅜㅜ

작동은 하는데 해당방법으로 해도 되는건지 의문점이 생기네요ㅜㅜ

제로초님 리액트 노드버드 타입스크립트 버전 강의는 제작 계획이 없는건가요??

다음 리뉴얼 때는 할 계획이 있습니다. 소스 코드는 github.com/zerocho/ts-nodebird에 일부 있습니다.

오 nestjs를 typescript기반으로 해서 프론트엔드도 타입스크립트로 바꾸고 싶은데

아직은 겁이 나에요 다름 리뉴얼 기대되네요~~^^ 감사합니다