0

I just started to learn Angular (using Version 19). So far the work with HttpClient goes on quite well. I've tried all kinds of requests with my backend (which is a Spring Boot application), all successful.

The problem comes when I tried to put a JWT token into the header of a request for authentication. No matter I add a headers object directly in the request call, or add the header via an interceptor, it seems that the header is never really set. When I check the filter at backend, it always points out that the header is null.

I just followed the standard way to implement the Http communication.

My interceptor looks like this:

import { Injectable } from '@angular/core';
import {
 HttpRequest,
 HttpHandler,
 HttpEvent,
 HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
 constructor() { }
 intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
 const token = localStorage.getItem("JWT_Token");
 if (token) {
 const authReq = request.clone({
 setHeaders: {
 Authorization: `Bearer ${token}`
 }
 });
 return next.handle(authReq);
 }
 return next.handle(request);
 }
}

My Http request:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Book } from '../dto/book';
@Injectable({
 providedIn: 'root'
})
export class BookService {
 constructor(private http : HttpClient) { }
 private apiUrl = 'http://localhost:8080/book';
 getAllBooks() : Observable<Book[]> {
 return this.http.get<Book[]>(this.apiUrl + '/all'); 
 }
 getBookById(id : string) : Observable<Book> {
 return this.http.get<Book>(this.apiUrl + '?id=' + id); 
 }
}

[This is the breakpoint at the moment when the interceptor kicks in. It seems the content of the intended header already exists in the "lazyUpdate". However, it does not take effect. Finally at the backend, Spring filter tells that header of this incoming request is null] (https://i.sstatic.net/KnZLZqpG.png)

WhatsThePoint
3,66512 gold badges35 silver badges58 bronze badges
asked Jan 6, 2025 at 1:55
3
  • How do you setup the HttpClient ? Commented Jan 6, 2025 at 2:51
  • In app.config.ts, I added two lines to providers: provideHttpClient(withInterceptorsFromDi()), {provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}, Commented Jan 6, 2025 at 19:56
  • 1
    The issue is solved. The above settings on angular is a bit old-style but basically correct. The real problem is on my backend, where I did not configure Spring Security to enable CORS. After that change, all becomes fine. Sorry for this question, and thank you all! Commented Jan 7, 2025 at 19:16

1 Answer 1

0

When i do it i just use headers instead of setHeaders, maybe this will give you a bit of luck so basically like this:

import { Injectable } from '@angular/core';
import {
 HttpRequest,
 HttpHandler,
 HttpEvent,
 HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
 constructor() { }
 intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
 const token = localStorage.getItem("JWT_Token");
 if (token) {
 const authReq = request.clone({
 headers: request.headers.set('Authorization', `Bearer ${token}`)
 });
 return next.handle(authReq);
 }
 return next.handle(request);
 }
}

now that is probably the same. Also if you are using standalone components which is default in angular 19. When you provide http make sure you provide it with:

provideHttpClient(withInterceptorsFromDi())

else the injection does not happen. To test if you injection even runs. Just put console.log into the intercepter and see if it fires, if it doesn't you probably need to adjust your provideHttpClient

answered Jan 6, 2025 at 9:42
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks much! I have tried all your suggestions, but the problem remains there. However, the interceptor really works. What confuses me most is as shown in the screenshot link of my question post: The intended header {'Authorization' : 'Bearer ...'} can be seen in the lazyUpdate of header, but finally header is still null. I don't understand the lazyUpdate mechanism.
Finally I fixed this. All that you suggested and I did with Angular are all right, just different syntax. The real problem lies in my backend, where I did not configure to enable CORS. So, my question here about Angular is not really correct. Thanks much anyway!
well at least it was fixed :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.