Search code examples
angularspringhttphttp-headersangular-http-interceptors

Angular & Spring - Headers not passed to backend


I'm trying to add an Authorization header in my http request from my Angular front-end, but it's not working : the backend don't receive this header.

When I watch on Chrome's console, I can see that the request is containing the header.
When I use Postman, the headers are okay in the backend.

Here is the Postman screenshot : enter image description here

Here is my Angular Interceptor :

    intercept(request: HttpRequest<any>, next: HttpHandler): 
        Observable<HttpEvent<any>> {
            if (!request.url.startsWith('http')) {
               if (localStorage.getItem('token')) {
                 let headers: HttpHeaders = request.headers;
                 headers = headers.set('Authorization', 'Bearer ' + 
                 localStorage.getItem('token'));

                 request = request.clone({
                     url: environment.backendUrl + request.url, headers
                 });
               }
            }

            console.log("headers are : ", request.headers);

            return next.handle(request).pipe(catchError((error: 
            HttpErrorResponse) => 
            {
               [...]
            })) as any;
   }

And here is my Spring filter:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    // Assume we have only one Authorization header value
    final Optional<String> token = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION));
    // Optional is empty
    [...]
}

Solution

  • My issue was on the WebSecurityConfig, I forgot to enable the CORS with this :

    http
          .cors().and()