I added in Security into my Spring app and suddenly I am getting CORS issues. I have tried many different CORS settings in Spring (see some of the commented out code). Nothing is working.
I am passing basic auth in my front end Angular app as so:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic mybase64basicauth'
})
};
...
this.campaignsSubscription = this.http.get<Campaign[]>(this.campaignsUrl, httpOptions)
And I have my app configured for CrossOrigin both locally and globally.
Global:
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("PUT", "DELETE", "GET", "OPTIONS", "POST", "PATCH")
.allowedHeaders("Authorization", "Content-Type")
// .allowedHeaders("Content-Type")
.allowCredentials(true).maxAge(3600);
// Add more mappings...
}
}
And locally:
/*@CrossOrigin(origins = "http://localhost:4200",
allowedHeaders = "*",
methods = { RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT},
allowCredentials = "true"
)*/
@CrossOrigin
@RestController
@RequestMapping("/api/campaign")
public class CampaignResource {
private CampaignRepository campaignRepository;
public CampaignResource(CampaignRepository campaignRepository) {
this.campaignRepository = campaignRepository;
}
@GetMapping("/all")
public Flux<Campaign> getAll() {
return campaignRepository
.findAll();
...
But I get these errors in the Chrome console:
zone.js:2969 OPTIONS http://localhost:8081/api/campaign/all 401 (Unauthorized)
'http://localhost:8081/api/campaign/all' from origin
'http://localhost:4200' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
I know the basic auth is correct as it works in Postman.