fix: improve error handling in authentication flow; validate access token and format, and ensure proper state verification in callback

This commit is contained in:
Usman Baig
2026-02-01 21:07:17 +01:00
parent 0dee4a699a
commit af5d9631e5
3 changed files with 54 additions and 42 deletions

View File

@@ -51,9 +51,14 @@ export async function exchangeAuthCode(code: string, codeVerifier: string, redir
}
const data: AuthResponse = await res.json()
if (!data?.access_token || typeof data.access_token !== 'string') {
throw new Error('Invalid token response')
}
// * Decode payload (without verification, we trust the direct channel to Auth Server)
const payloadPart = data.access_token.split('.')[1]
if (!payloadPart) {
throw new Error('Invalid token format')
}
const payload: UserPayload = JSON.parse(Buffer.from(payloadPart, 'base64').toString())
// * Set Cookies

View File

@@ -43,30 +43,24 @@ function AuthCallbackContent() {
const code = searchParams.get('code')
const state = searchParams.get('state')
// * Skip if params are missing (might be initial render before params are ready)
if (!code || !state) return
processedRef.current = true
const storedState = localStorage.getItem('oauth_state')
const codeVerifier = localStorage.getItem('oauth_code_verifier')
if (!code || !state) {
setError('Missing code or state')
if (!codeVerifier) {
setError('Missing code verifier')
return
}
if (state !== storedState) {
console.error('State mismatch', { received: state, stored: storedState })
setError('Invalid state')
return
}
if (state !== storedState) {
console.error('State mismatch', { received: state, stored: storedState })
setError('Invalid state')
return
}
if (!codeVerifier) {
setError('Missing code verifier')
return
}
processedRef.current = true
const exchangeCode = async () => {
try {