I can register, update and delete everything. However, when I will
request security, I'm blocked by CORS.
Access to XMLHttpRequest at 'http://localhost:8080/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My cors config class:
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfiguration(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowedOrigins("http://localhost:4200");
}
};
}
In SecurityConfig.class:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//resguarda aplica??es web dentro do projeto
.csrf().disable()
.cors()
.and()
.sessionManagement()
//aplica??o n?o guardará sess?es (será pelo token)
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
authService.ts:
tentarLogar(username: string, password: string): Observable<any>{
const params = new HttpParams()
.set('username', username)
.set('password', password)
.set('grant_type', 'password')
const headers = {
'Authorization': 'Basic ' + btoa(`${this.clientID}:${this.clientSecret}`),
'Content-Type': 'application/x-www-form-urlencoded'
}
return this.http.post(this.tokenURL, params.toString, {headers})
}
If needs more some code please tell me.
But as I said, with this configuration I can access the API, the real problem is not being able to access localhost:8080/oauth/token
to get the JWT token.
EDIT:
new CorsConfiguration.class:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebConfig implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
question from:
https://stackoverflow.com/questions/65932383/cors-policy-and-spring-security