I have a simple Angular app that perform a post request to an endpoint this way:
login(username:string, password:string){
return this.http.post<String>('localhost:9090/helios-admin/api/auth/login',{
"username": username,
"password":password
});
}
but the error of CORS policy is thrown. In my Spring application, that is the one the expose the endpoint, I've set the cors mappings this way:
@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*")
.allowedMethods("GET","POST", "OPTIONS");
}
}
I've encountered the same problem but with another application, asked a question, got the response and used it correctly. Now with this angular project it doesn't work. Do I have to change something?
EDIT This is my controller in Spring Boot
@CrossOrigin
@PostMapping(PathConstants.LOGIN_ACTION)
@ApiOperation("Login into Helios administrational console.")
@Override
public ResponseEntity<?> autenticate(@Valid @RequestBody LoginRequest request) {
Authentication auth = authManager
.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
SecurityContextHolder.getContext().setAuthentication(auth);
String token = jwtProvider.generateToken(auth);
return ResponseEntity.ok(new JwtAuthResponse(token));
}
UPDATE
The problem was in the url: it wanted a 'http://localhost:9090/helios-admin/api/auth/login'
, so with http. Stupid error.
Now I have a new one.
It says:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So I've added:
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
and in angular
this.httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'})
};
return this.http.post<String>('http://localhost:9090/helios-admin/api/auth/login',{
"username": username,
"password":password
}, this.httpOptions).pipe(catchError(this.errorHandler));
but doesn't work.