Reputation: 950
I have a basic spring boot rest application and angular application. (Using JWT)
However, I can not make any request because of this error:(even I add "Access-Control-Allow-Origin", "*"
to response header
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/login. (Reason: CORS request did not succeed).
Here is the security configuration:
public class AuthTokenFilter extends OncePerRequestFilter {
// ...
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers(WebUrls.API.API + WebUrls.LOGIN.LOGIN,
WebUrls.API.API + WebUrls.LOGIN.REGISTER,
WebUrls.API.API + WebUrls.LOGIN.REFRESH_TOKEN)
.permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
Here is the place where I am adding cors headers:
@Component
public class MyCorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "*");
filterChain.doFilter(servletRequest, servletResponse);
}
}
Upvotes: 1
Views: 2183
Reputation: 133
Please try the below configuration to make this work. This enables CORS requests from any origin to any endpoint in the application.
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
Upvotes: 2