-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat/auth 로그인 페이지의 alert를 Mui Alert로 변경과 토큰 검증 및 갱신 자동화 #204
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0d4865d
[feat] 로그인 페이지의 alert를 Mui Alert로 변경
allone9425 d27ac91
[feat] 로그인 상태 유지
allone9425 d84f633
Merge branch 'dev' of https://github.com/allone9425/Dicotown into fea…
allone9425 7423a91
[feat] 토큰 검증
allone9425 fb55ac1
Merge branch 'dev' of https://github.com/allone9425/Dicotown into fea…
allone9425 34b7b79
Merge branch 'dev' of https://github.com/allone9425/Dicotown into fea…
allone9425 1495b38
[feat] axios Interceptor로 토큰 검증 및 갱신 자동화
allone9425 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/* | ||
이 인스턴스가 필요한 이유 : | ||
-------------------------------------------------------- | ||
<로직> | ||
토큰이 유효한가? | ||
토큰이 유효하지 않다면 리프레시 토큰으로 발급 | ||
발급실패 시 로그인페이지로 이동 | ||
-------------------------------------------------------- | ||
axios 인터셉터로 위의 로직대로 코드 작성 하다가 요청 인터셉터가 계속해서 같은 요청을 반복하는 상황이 발생, | ||
token.ts의 두 함수(validateAccessToken, refreshAccessToken)에서 요청을 보내는 부분이 인터셉터에 의해 다시 가로채지고 있는 것으로 추정 | ||
이를 해결하기 위한 방법으로 아래의 인스턴스를 별도 만들어서 해결함 | ||
*/ | ||
import axios from "axios"; | ||
|
||
const axiosInstance = axios.create({ | ||
baseURL: "http://kpring.duckdns.org", | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
}); | ||
|
||
export default axiosInstance; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import axiosInstance from "./axiosInstance"; | ||
|
||
// 토큰 검증 API | ||
export async function validateAccessToken(token: string): Promise<boolean> { | ||
console.log("액세트 토큰이 유효한가?:", token); | ||
try { | ||
const response = await axiosInstance.post( | ||
"/auth/api/v2/validation", | ||
{}, | ||
{ | ||
headers: { | ||
Authorization: `Bearer ${token}`, | ||
}, | ||
} | ||
); | ||
console.log("액세스 토큰 응답 상태(status):", response.status); | ||
console.log("액세스토큰 응답 데이터:", response.data); | ||
|
||
if (response.status === 200) { | ||
console.log("토큰 검증 성공:", response.data); | ||
return true; | ||
} else { | ||
console.error("토큰 검증 실패:", response.data); | ||
return false; | ||
} | ||
} catch (error) { | ||
console.error("토큰 검증 중 오류 발생:", error); | ||
return false; | ||
} | ||
} | ||
|
||
// 새로운 accessToken 요청 | ||
export async function refreshAccessToken( | ||
refreshToken: string | ||
): Promise<{ accessToken: string; refreshToken: string } | null> { | ||
console.log("리프레시 토큰으로 새로운 액세스 토큰 요청:", refreshToken); | ||
try { | ||
const response = await axiosInstance.post( | ||
"/auth/api/v1/access_token", | ||
{ refreshToken }, | ||
{ | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
} | ||
); | ||
console.log("새로운 액세스 토큰 응답 상태(status):", response.status); | ||
console.log("새로운 액세스 토큰 응답 데이터 :", response.data); | ||
|
||
if (response.status === 200) { | ||
console.log("accessToken 갱신 성공:", response.data); | ||
return response.data.data; | ||
} else { | ||
console.error("accessToken 갱신 실패:", response.data); | ||
return null; | ||
} | ||
} catch (error) { | ||
console.error("API 호출 중 오류 발생:", error); | ||
return null; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,23 @@ | ||
import create from "zustand"; | ||
|
||
interface LoginState { | ||
export interface LoginState { | ||
accessToken: string; | ||
refreshToken: string; | ||
setTokens: (accessToken: string, refreshToken: string) => void; | ||
clearTokens: () => void; | ||
} | ||
|
||
export const useLoginStore = create<LoginState>((set) => ({ | ||
accessToken: "", | ||
refreshToken: "", | ||
accessToken: localStorage.getItem("dicoTown_AccessToken") || "", | ||
refreshToken: localStorage.getItem("dicoTown_RefreshToken") || "", | ||
setTokens: (accessToken, refreshToken) => { | ||
set({ accessToken, refreshToken }); | ||
localStorage.setItem("dicoTown_AccessToken", accessToken); | ||
localStorage.setItem("dicoTown_RefreshToken", refreshToken); | ||
}, | ||
clearTokens: () => { | ||
set({ accessToken: "", refreshToken: "" }); | ||
localStorage.removeItem("dicoTown_AccessToken"); | ||
localStorage.removeItem("dicoTown_RefreshToken"); | ||
}, | ||
})); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저는 axios 인스턴스를 새로 만들어서 interceptor로 토큰 검증 로직짜고, 만든 인스턴스를 가져다 쓰는 쪽으로 사용했었는데,
여기다가 함수 호출해서 interceptor 설정하는 방법도 있는지 몰랐어요. 이런 방법도 있었군요 신기하네요
주석도 다 달아 놓으셔서 이해하기 편했습니다!
근데 안쓰는 console.log()가 메모리 누수나 성능에 안좋아서 필요 없는 부분+ 테스트 끝난 부분 있으시면 지우는게 좋대요
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
console.log()의 경우 로그인 관련 기능개발이 완전히 다 끝나면 지우도록 하겠습니다 :) 조언 감사합니다!