Enhance authentication flow by adding token refresh mechanism and improving error handling. Implement checks to prevent authentication loops during API calls and ensure token is updated before requests. This improves user experience and security in the application.
This commit is contained in:
@@ -31,15 +31,35 @@ export const api = createApi({
|
||||
) => {
|
||||
const response = await fetch(input, init)
|
||||
|
||||
if (response.status === 403) keycloak.login()
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
const { isAuthLoopBlocked, recordAuthAttempt } = await import('../../utils/authLoopGuard')
|
||||
|
||||
if (!isAuthLoopBlocked()) {
|
||||
recordAuthAttempt()
|
||||
keycloak.login()
|
||||
} else {
|
||||
console.error('Auth loop detected, not redirecting to login')
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json;charset=utf-8',
|
||||
},
|
||||
prepareHeaders: (headers) => {
|
||||
headers.set('Authorization', `Bearer ${keycloak.token}`)
|
||||
prepareHeaders: async (headers) => {
|
||||
try {
|
||||
// Обновить токен, если он истекает в течение 30 секунд
|
||||
await keycloak.updateToken(30)
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh token:', error)
|
||||
}
|
||||
|
||||
if (keycloak.token) {
|
||||
headers.set('Authorization', `Bearer ${keycloak.token}`)
|
||||
}
|
||||
|
||||
return headers
|
||||
},
|
||||
}),
|
||||
tagTypes: ['Task', 'Chain', 'User', 'Submission', 'Stats'],
|
||||
|
||||
@@ -34,9 +34,22 @@ export const mount = async (Component, element = document.getElementById('app'))
|
||||
|
||||
recordAuthAttempt()
|
||||
await keycloak.init({
|
||||
onLoad: 'login-required'
|
||||
onLoad: 'login-required',
|
||||
checkLoginIframe: false
|
||||
})
|
||||
|
||||
// Настройка автоматического обновления токена
|
||||
setInterval(() => {
|
||||
keycloak.updateToken(70).then((refreshed) => {
|
||||
if (refreshed) {
|
||||
console.log('Token was successfully refreshed')
|
||||
}
|
||||
}).catch(() => {
|
||||
console.error('Failed to refresh token, redirecting to login')
|
||||
keycloak.login()
|
||||
})
|
||||
}, 60000) // Проверять каждую минуту
|
||||
|
||||
const userInfo = await keycloak.loadUserInfo()
|
||||
|
||||
if (userInfo && keycloak.tokenParsed) {
|
||||
|
||||
Reference in New Issue
Block a user