This is my SecurityConfiguration
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
private final TokenService tokenService;
public SecurityConfiguration(TokenService tokenService) {
this.tokenService = tokenService;
}
@Bean
public WebMvcConfigurer corsMappingConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors().disable()
.csrf().disable()
.authorizeRequests().requestMatchers("/user/login", "/user/register")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().apply(new TokenFilterConfigurer(tokenService));
return http.build();
}
}
This is token filter using Auth0
public class TokenFilter extends GenericFilter {
private final TokenService tokenService;
public TokenFilter(TokenService tokenService) {
this.tokenService = tokenService;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String authorization = request.getHeader("Authorization");
if (ObjectUtils.isEmpty(authorization)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
if (!authorization.startsWith("Bearer ")) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
String token = authorization.substring(7);
DecodedJWT decoded = tokenService.verify(token);
if (decoded == null) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
Long principal = decoded.getClaim("principal").asLong();
String role = decoded.getClaim("role").asString();
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(role));
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, "(protected)", authorities);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(authentication);
filterChain.doFilter(servletRequest, servletResponse);
}
}
Here is my error
Access to fetch at 'http://localhost:8080/skill/get' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
the path "/user/login", "/user/register" still work.
I have try to disable it but it doesn't work. I want to know how to disable the CORS.