简体   繁体   中英

Angular sends null Authorization Header

I am trying to send a request with an authorization header with Angular to a Spring backend.

export class TokenInterceptor implements HttpInterceptor{

    constructor(public sharedService : SharedService){}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const jwtToken = this.sharedService.getJwtToken();

        if(jwtToken){
            req = this.addToken(req, jwtToken)
        }

        return next.handle(req)
   }

   addToken(req: HttpRequest<any>, jwtToken: any){
        return req.clone({
            headers: req.headers.append('Authorization', 'Bearer ' + jwtToken)
        });
   }
}

This is what my interceptor looks like. If I try to console.log() the authorization header before returning the next().handle, I can see the correct token inside the request. The problem is that the backend instead recieves a null Authorization header.

Inside by backend I have a doFilterInternal() method that filters any request and gets the Authentication header. I don't think the problem is inside this filter because the request sent with Postman are handled correctly. I have already enabled CORS on my backend

@Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true)
                .maxAge(3600L);
}

I believe token is not set, because headers property is read-only .

Try to use setHeaders property of clone method argument:

addToken(req: HttpRequest<any>, jwtToken: any){
   return req.clone({
      setHeaders: { Authorization: 'Bearer ' + jwtToken }
   });
}

After banging my head against the wall for several hours I found the solution. When creating a class and implementing the WebMvcConfigurer (to enable CORS) this is right and it SHOULD work.

public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true)
                .maxAge(3600L);
    }
}

BUT this isn't enough, since I had to enable CORS also into the security config chain

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http.cors().and().csrf().disable();

    return http.build();
}

by tiping http.cors()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM