diff --git a/src/shared/api/http.test.ts b/src/shared/api/http.test.ts index e0c6d792..80ec5b03 100644 --- a/src/shared/api/http.test.ts +++ b/src/shared/api/http.test.ts @@ -18,6 +18,26 @@ afterEach(() => { }) describe('API error diagnostics', () => { + it('does not attach a stale access token to anonymous authentication requests', async () => { + localStorage.setItem('cc-admin-token', 'stale-large-token') + let authorization: unknown + http.defaults.adapter = async (config) => { + authorization = config.headers.Authorization + return { + status: 200, + statusText: 'OK', + headers: {}, + config, + data: { code: '200', message: 'success', data: null }, + } + } + + await http.post('/auth/login', { username: 'operator', password: 'secret' }) + + expect(authorization).toBeUndefined() + localStorage.removeItem('cc-admin-token') + }) + it('treats only body code 200 as success', () => { expect(unwrapApiResponse({ code: '200', message: 'success', data: { id: '1' } })) .toEqual({ id: '1' }) diff --git a/src/shared/api/http.ts b/src/shared/api/http.ts index 7d87d5e4..fadad2a1 100644 --- a/src/shared/api/http.ts +++ b/src/shared/api/http.ts @@ -59,7 +59,9 @@ export function registerAuthSessionExpiredHandler(handler: AuthSessionExpiredHan http.interceptors.request.use((config) => { const token = localStorage.getItem('cc-admin-token') - if (token) { + const isAnonymousAuthEndpoint = typeof config.url === 'string' + && ['/auth/login', '/auth/refresh', '/auth/register'].includes(config.url) + if (token && !isAnonymousAuthEndpoint) { config.headers.Authorization = `Bearer ${token}` } return config