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);
}
CodePudding user response:
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 }
});
}
CodePudding user response:
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()