Issue
I know... The CORS problematic is a well discussed topic. After searching for hours and hours for the solution of my problem, I ask you now for help :)
I have an ionic angular app and a spring boot application for my backend. The backend is hosted on a public server (with a domain) and with a letsencrypt ssl encryption.
All was working fine until I've added a custom header. I receive for each request a cors error:
Access to XMLHttpRequest at 'https://www.BACKEND_URL.com:5000/healthstatus'
from origin 'http://localhost:8100' 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've added the custom header argument with an interceptor like this:
import {Injectable} from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {Observable} from "rxjs";
import {AuthService} from "../services/auth.service";
@Injectable() export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('####: interceptor: addHeader');
request = request.clone({ setHeaders: { Authorization: `Bearer TEST-TOKEN` } });
return next.handle(request);
}
}
On the controller I've added also the CrossOrigin annotation
@CrossOrigin
@Controller
Only when I edit the header I receive the CORS error. Can you give me an advice? Is there another way to add my token to the request?
Thanks in advance
Solution
Finally I've found the solution!
In Spring boot I'am using a "HandlerInterceptor". This interceptor allows only requests which has my token in the header.
When the browser asks the server for some cors info, the browser sends a OPTIONS-call to the backend server. This option call was also be rejected and thus not able to retrieve the allowed methods/headers/origins...
My code looks like this
if (request.getMethod().equals("OPTIONS")) {
response.setHeader("Access-Control-Allow-Origin", "*");
//I've changed the 'Authorization' header to 'token' (at the end of the following codeline)
response.setHeader("Access-Control-Allow-Headers", "AuthID,Origin,X-Requested-With,Content-Type,Accept,token");
//After that, continue without checking if the request is correct
return true;
} else {
//check if the request-header contains my token...
}
If you have implemented the spring boot security you should adjust the following code:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers("/", "/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated();
http.csrf().disable();
http.headers().frameOptions().disable();
}
Answered By - Elchman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.