Issue
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);
}
Solution
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()
Answered By - user19845343
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.