Issue
I am working on a web-based app with angular and spring boot. Jwt is generated and the user can log in but when I want to get user information after login it shows this error on the browser:
Access to XMLHttpRequest at 'http://localhost:8080/api/user/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And in IntelliJ it says: JWT Token does not begin with Bearer String
What should I do?
Solution
One way to enable Cross-origin Reference Sharing in Spring Security would be:
In your web security configuration class (annotated with @EnableWebSecurity
), you need to first enable CORS on the HttpSecurity
object:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
...
}
Then add a @Bean
annotated method in the same class which sets some configurations (like allowed origins and response headers) and returns CorsConfigurationSource
:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
config.setAllowCredentials(true);
config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
Regarding "JWT Token does not begin with Bearer String", you need to send Bearer
along with JWT token(space-separated) in the request Authorization
header:
Authorization: Bearer xxxxx.yyyyy.zzzzz
Answered By - Mo_-
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)