To fix this error, I used to enable spring security I have added below class in my spring boot application.
Here my API is running in 8080 and angular in 4200
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests().
antMatchers( "/**")
.permitAll()
.anyRequest()
.authenticated();
}
}
And my controller is like
@RestController
public class AuthenticationController {
@RequestMapping(method = RequestMethod.GET, value = "/login")
public String userValidation(){
return "valid user";
}@GetMapping(path = "/basicauth")
public AuthenticationBean basicauth() {
return new AuthenticationBean("You are authenticated");
}
}
After this I got below error,
Access to XMLHttpRequest at 'http://localhost:8080/basicauth' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET http://localhost:8080/basicauth net::ERR_FAILED 401
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:8080/basicauth', ok: false, …}
Resolve this error I added below code in my controller class.
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class AuthenticationController {//your methods are here...!}After this change the same call give response like below,
Thank you!