Kenbrnbe
Kenbrnbe

Reputation: 33

Angular 17 Interceptor Not Adding Bearer Token on Initial Login Request

I'm working on an Angular 17 application where I'm trying to add an Authorization Bearer token to the request headers upon login. However, I'm facing an issue where the HttpInterceptor retrieves null from localStorage on the first login attempt, which means the Bearer token isn't added to the request header during the initial login request. On subsequent logins, the token is added successfully since it's already present in localStorage.

I suspect the interceptor is calling localStorage.getItem('token') before the token is saved after a successful login. Is there a better approach to ensure the token is set correctly in the interceptor on the first login attempt?

intercetor

export const AuthInterceptor: HttpInterceptorFn = (
  req: HttpRequest<any>,
  next: HttpHandlerFn
): Observable<HttpEvent<any>> => {
  const token = inject(AuthService).getToken();

  if (token) {
    const authRequest = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`),
    });
    return next(authRequest);
  }

  return next(req);
};

services

loginAccount(payload: any): Observable<any> {
  return this.http
    .post<any>(environment.adminServerUrl + 'login', payload, {
      headers: this.headers,
    })
    .pipe(map((response) => response));
}

saveToken(token: string): void {
  localStorage.setItem('token', token);
}

getToken(): string | null {
  return localStorage.getItem('token');
}

login component

login() {
  const payload = this.accountLogin.value;

  this.authService.loginAccount(payload).subscribe({
    next: (data) => {
      console.log('Login successful:', data);
      this.authService.saveToken(data.payload);
    },
  });
}

Issue:

The interceptor runs before the token is saved to localStorage during the first login attempt, so the Authorization header is not added. On subsequent logins, the token is already present in localStorage, so the header is added correctly.

Questions:

Is there a way to ensure the token is available in the interceptor during the initial login request? Are there better practices for handling token storage and retrieval in Angular 17 interceptors? Any advice or suggestions would be greatly appreciated!

Upvotes: 1

Views: 85

Answers (0)

Related Questions