Hard
Fix Race Conditions in JWT Token Refresh Implementation with Authentication Service
You're implementing an authentication system that needs to manage JWT tokens and handle automatic token refresh. What's wrong with this implementation?
1class AuthService {2 constructor() {3 this.token = localStorage.getItem('token');4 this.refreshToken = localStorage.getItem('refreshToken');5 }67 async request(url, options = {}) {8 if (!this.token) throw new Error('Not authenticated');910 const response = await fetch(url, {11 ...options,12 headers: {13 ...options.headers,14 'Authorization': `Bearer ${this.token}`15 }16 });1718 if (response.status === 401) {19 await this.refreshTokens();20 return this.request(url, options);21 }2223 return response;24 }2526 async refreshTokens() {27 const response = await fetch('/api/refresh', {28 method: 'POST',29 headers: {30 'Content-Type': 'application/json'31 },32 body: JSON.stringify({33 refreshToken: this.refreshToken34 })35 });3637 if (!response.ok) {38 throw new Error('Failed to refresh token');39 }4041 const { token, refreshToken } = await response.json();42 this.token = token;43 this.refreshToken = refreshToken;44 localStorage.setItem('token', token);45 localStorage.setItem('refreshToken', refreshToken);46 }47}