-
Notifications
You must be signed in to change notification settings - Fork 1
bugfix: #105 소셜로그인 이후 토큰이 있어도 401로 떨어지는 현상해결 #112
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
Conversation
소셜로그인 이후 토큰이 있어도 401로 떨어지는 현상해결
WalkthroughThe changes refactor API instance creation and token handling by explicitly configuring Axios headers and updating token storage logic. The OAuth2 redirect component now reads the token from a different query parameter, saves it in localStorage, and synchronizes it with a new atom state. A new atom for token management is introduced. Changes
Sequence Diagram(s)sequenceDiagram
participant Browser
participant Oauth2Redirect
participant LocalStorage
participant UserStore
participant Router
Browser->>Oauth2Redirect: Loads with ?token=...
Oauth2Redirect->>Browser: Reads token from window.location.search
Oauth2Redirect->>LocalStorage: Stores token under "accessToken"
Oauth2Redirect->>UserStore: Sets loginState and tokenState
Oauth2Redirect->>Router: Navigates to "/"
sequenceDiagram
participant App
participant AxiosInstance
participant LocalStorage
App->>LocalStorage: Reads "accessToken"
App->>AxiosInstance: Creates instance with headers (Authorization if token exists)
AxiosInstance-->>App: Ready for authenticated API calls
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/app/oauth2/redierct/index.tsx (1)
29-29: Consider showing loading state during redirect processing.Returning
nullmeans users won't see any feedback during the OAuth2 redirect processing. Consider showing a loading indicator for better UX.- return null; + return <div>Processing login...</div>;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/api/index.ts(2 hunks)src/app/oauth2/redierct/index.tsx(1 hunks)src/store/user/index.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/app/oauth2/redierct/index.tsx (2)
src/store/user/index.ts (2)
loginState(3-3)tokenState(4-4)src/utils/constant.ts (1)
ACCESS_TOKEN(16-16)
src/api/index.ts (1)
src/utils/constant.ts (1)
ACCESS_TOKEN(16-16)
🔇 Additional comments (6)
src/store/user/index.ts (1)
3-4: LGTM! Clean token state management implementation.The new
tokenStateatom usingatomWithStorageprovides a clean way to manage token persistence. The implementation correctly uses the same storage key ("accessToken") and initializes with an appropriate default value.src/app/oauth2/redierct/index.tsx (2)
13-14: Verify the URL parameter change from "accessToken" to "token".The parameter extraction has changed from "accessToken" to "token". Please confirm this aligns with the OAuth2 provider's redirect URL format.
22-26: Good error handling improvement.The error handling now properly clears both login and token states, which ensures a clean state when authentication fails.
src/api/index.ts (3)
27-27: Excellent addition for CORS cookie support.The
withCredentials: trueoption is essential for enabling CORS cookie transmission, which helps resolve authentication issues in cross-origin scenarios.
51-54: Good token handling in request interceptor.The request interceptor correctly reads the fresh token from localStorage on each request, ensuring the Authorization header is always up-to-date.
130-137: Clean refactoring of interceptor setup.The parameter renaming from
axiosInstancetoinstanceimproves clarity and avoids confusion with the module-level variable.
| localStorage.setItem(ACCESS_TOKEN, token); | ||
| setToken(token); |
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.
💡 Verification agent
🧩 Analysis chain
Critical: Token key inconsistency between localStorage and atom state.
There's a mismatch in token storage keys:
localStorage.setItem(ACCESS_TOKEN, token)uses theACCESS_TOKENconstantsetToken(token)sets thetokenStateatom which uses "accessToken" as the storage key- The relevant code snippet shows
ACCESS_TOKEN = "access_token"(with underscore)
This inconsistency will cause synchronization issues between localStorage and the atom state.
To fix this, either:
- Use the same key for both storage mechanisms, or
- Use only the atom state and let
atomWithStoragehandle localStorage automatically
- localStorage.setItem(ACCESS_TOKEN, token);
- setToken(token);
+ setToken(token); // atomWithStorage will handle localStorage automatically🏁 Script executed:
#!/bin/bash
# Verify the ACCESS_TOKEN constant value and usage across the codebase
echo "Checking ACCESS_TOKEN constant definition:"
rg "ACCESS_TOKEN.*=" --type ts
echo -e "\nChecking ACCESS_TOKEN usage:"
rg "ACCESS_TOKEN" --type ts -A 2 -B 2Length of output: 3738
🏁 Script executed:
#!/bin/bash
# Search for tokenState definition in the codebase
rg "tokenState" -n --type ts
# Show the file containing tokenState to inspect its definition
rg -A5 "tokenState" --type tsLength of output: 1207
Ensure consistent token storage key across localStorage and atom state
The ACCESS_TOKEN constant is defined as btoa("FLOWBIT_ACT") (e.g. "RkxPV0JJVF9BQ1Q="), while your tokenState atom persists under "accessToken". This means:
- API calls (
localStorage.getItem(ACCESS_TOKEN)) will never see the value stored byatomWithStorage("accessToken", …) atomWithStoragewill never read or write the key your API relies on
To resolve, pick one shared key and apply it everywhere:
• src/utils/constant.ts
- const ACCESS_TOKEN = btoa("FLOWBIT_ACT");
+ export const ACCESS_TOKEN = "accessToken";• src/store/user/index.ts
- export const tokenState = atomWithStorage("accessToken", "");
+ export const tokenState = atomWithStorage(ACCESS_TOKEN, "");• src/app/oauth2/redirect/index.tsx
- localStorage.setItem(ACCESS_TOKEN, token);
- setToken(token);
+ setToken(token); // atomWithStorage will now handle both state and localStorage under ACCESS_TOKENOr, if you prefer to keep the base64 key, swap the "accessToken" literal in your atom to use ACCESS_TOKEN instead, and remove direct localStorage calls in favor of setToken(token).
🤖 Prompt for AI Agents
In src/app/oauth2/redierct/index.tsx around lines 17 to 18, there is an
inconsistency between the localStorage key ACCESS_TOKEN and the atom state key
"accessToken" used by tokenState. To fix this, unify the storage key by either
changing the atomWithStorage key to use ACCESS_TOKEN or by removing direct
localStorage calls and relying solely on the atomWithStorage state with the
ACCESS_TOKEN key. Ensure that both localStorage and atom state use the exact
same key constant to maintain synchronization.
| const headers: RawAxiosRequestHeaders = { | ||
| "Content-Type": "application/json", | ||
| }; | ||
|
|
||
| headers: { | ||
| "Content-Type": "application/json", | ||
| }, | ||
| const token = localStorage.getItem(ACCESS_TOKEN); | ||
| if (token) { | ||
| headers.Authorization = `Bearer ${token}`; | ||
| } |
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.
🛠️ Refactor suggestion
Remove duplicate Authorization header logic.
The Authorization header is being set twice:
- Here at instance creation (lines 19-22)
- In the request interceptor (lines 51-54)
The static header setting at instance creation won't update when the token changes, making it unreliable. The request interceptor already handles this correctly by reading the fresh token on each request.
-const headers: RawAxiosRequestHeaders = {
- "Content-Type": "application/json",
-};
-
-const token = localStorage.getItem(ACCESS_TOKEN);
-if (token) {
- headers.Authorization = `Bearer ${token}`;
-}
+const headers: RawAxiosRequestHeaders = {
+ "Content-Type": "application/json",
+};📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const headers: RawAxiosRequestHeaders = { | |
| "Content-Type": "application/json", | |
| }; | |
| headers: { | |
| "Content-Type": "application/json", | |
| }, | |
| const token = localStorage.getItem(ACCESS_TOKEN); | |
| if (token) { | |
| headers.Authorization = `Bearer ${token}`; | |
| } | |
| const headers: RawAxiosRequestHeaders = { | |
| "Content-Type": "application/json", | |
| }; |
🤖 Prompt for AI Agents
In src/api/index.ts around lines 15 to 22, remove the logic that sets the
Authorization header using the token from localStorage during instance creation.
This is redundant because the request interceptor (lines 51-54) already sets the
Authorization header dynamically on each request with the latest token. Deleting
this static header assignment ensures the Authorization header always uses the
current token.
joeunSong
left a comment
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.
고생하셨습니다~
소셜로그인 이후 토큰이 있어도 401로 떨어지는 현상해결
목적
작업 내용
API 요청 시 인증 헤더 설정 방식 개선
OAuth2 리다이렉트 처리 로직 개선
토큰 관리 방식 일원화
필수 리뷰어
이슈 번호
Summary by CodeRabbit