I am creating a sample application using Spring Boot and Angular 7. In spring boot I am converting http to https. In angular application the client side post functionality cannot call the server Api post method.
It throws the below error
Access to XMLHttpRequest at 'https://localhost:8082/Demo/list' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Client Side Angular 7
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
firstClick() {
return console.log('clicked');
}
getList() {
return this.http.get('https://localhost:8082/Demo/list');
}
}
Client Side
constructor(private data: DataService) {}
ngOnInit() {
this.data.getList().subscribe(data => {
this.tempList = data
console.log(this.tempList);
});
}
Server
@CrossOrigin(origins = "http://localhost:4200")
@Controller
As per Spring Security you should enable localhost domain to allow access, or allow all domain to access(not secure)
https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors().and()
...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Updated:
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors