Reputation: 181
I'm having issues with the CORS headers when sending an HTTP request from my Angular 7 application (hosted on http://localhost:4200) to my Spring-Boot application (hosted on https://localhost:8924) from Firefox.
I have a CORS filter in my Spring-Boot application that is added to my request:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
response.addIntHeader("Access-Control-Max-Age", 3600);
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
}
else
{
filterChain.doFilter(request, response);
}
}
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.addFilterBefore(corsFilter(), SessionManagementFilter.class);
http.csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**","/api/MentorCalendar","/api/user/role/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
When sending the request, the Firefox console returns this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8924/api/auth/signin. (Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed).
Commenting out the Access-Control-Allow-Origin:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
// response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
response.addIntHeader("Access-Control-Max-Age", 3600);
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
}
else
{
filterChain.doFilter(request, response);
}
}
}
Returns this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8924/api/auth/signin. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
src/app/home/login.component.ts extract
export class LoginComponent {
constructor(private LoginService: LoginService, private router: Router) {}
login(inputUsername, inputPassword){
this.LoginService.login({username: inputUsername, password: inputPassword})
.subscribe(data => {
localStorage.setItem("jwtToken", data.accessToken);
src/app/home/login.service.ts
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable()
export class LoginService {
loginUrl = "http://localhost:8924/api/auth/signin";
constructor( private http: HttpClient ) {}
login(loginCreds: any): Observable<any> {
return this.http.post<any>(this.loginUrl, loginCreds, httpOptions);
}
}
How does the response.addHeader("Access-Control-Allow-Origin", "*"); line set multiple headers when included but none when I remove it?
Upvotes: 0
Views: 8616
Reputation: 41
In my case this happens when i set both CORS support in nginx conf file and Django middleware.
Nginx part:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
Django part:
MIDDLEWARE = (
'corsheaders.middleware.CorsMiddleware',
Solution was very simple - i just remove CORS part in nginx and all works perfectly
location / {
uwsgi_pass django_upstream;
include uwsgi_params;
}
Upvotes: 0
Reputation: 181
This has solved the issue for me:
if(!response.containsHeader("Access-Control-Allow-Origin"))
{
response.addHeader("Access-Control-Allow-Origin", "*");
}
Not the ideal way to get it to work
Upvotes: 0
Reputation: 145
Did you try enabling @CrossOrigin() in you springboot controller. Below is the basic snippet.
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
For more info visit Enabling CORS
I had the same problem. It was solved by above solution. You must not be CORS problem when using Internet Explorer.
Upvotes: 1