Asked  12 Months ago    Answers:  5   Viewed   15 times

everyone. I'm new to Angular 2 and Spring Framework. I'm trying a simple get request with an authorization header (basic auth).

I'm using Spring Boot (1.2.6.RELEASE), which can also be relevant. My CORS configuration looks like this.

public class SimpleCorsFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(SimpleCorsFilter.class);

public SimpleCorsFilter() {"SimpleCORSFilter init");

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, authorization, x-auth-token");

    chain.doFilter(req, res);

public void init(FilterConfig filterConfig) {

public void destroy() {


And here's what it looks like from the client side

    this.headers.append('Authorization', 'Basic dXNlcjphZG1pbg==');
    return this.http
            .get(`http://localhost:8080/api/login?username=${username}`, {headers : this.headers} )
            .map(response => response.json().data as any);

I keep getting:

XMLHttpRequest cannot load http://localhost:8080/api/login?username=user. Response for preflight has invalid HTTP status code 401

Please help, i don't know what i'm missing... I checked around a lot of posts already but couldn't get there...



avoid filtering and set status 200 when http method is OPTIONS

if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
} else {
    chain.doFilter(req, res);
Friday, June 25, 2021

I finally found a work around. what i did is i removed custom headers from web.config file. i.e,

    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token"/>
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    <add name="Content-Type" value="application/json"/>

    <add name="Access-Control-Allow-Credentials" value="true" />

This content i removed

and in WebApiConfig.cs i did following changes

var enableCorsAttribute = new EnableCorsAttribute(origins:"*",headers:"*",methods:"*");

            var json = config.Formatters.JsonFormatter;

            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;


and Controller Looks like this.

[EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
    public class Add_Client_Controller : ApiController

        public string PostGoals(string goal)
            Goal g = new Goal();
            g.Goals = goal;
            int res = db.SaveChanges();

            return ("Success");

and Angular POST Method looks like following


  let headers : Headers= new Headers();

      let options = new RequestOptions({ headers: headers });
       .map(res =>  res.json());

This is work around to send data with URL.

Friday, July 30, 2021

Nothing worked for me except the below; Where I had to import Microsoft.Owin.Cors and add this line of code at the top of ConfigureAuth method in Startup.Auth.cs of Web API.


Please note:- remove all the settings for enabling CORS from Web.config and WebApiConfig.cs. Otherwise it will complain about duplicate implementation.

Happy Coding :-)

Wednesday, October 27, 2021

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $ = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation:

Kudos to this answer for showing me the way. AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

Wednesday, December 1, 2021

Please read more about Preflight requests.

They simply suggest the browser if the server supports a cross-origin request. The response to such OPTIONS requests should good (i.e. < 400).

I think the statement filterChain.doFilter(servletRequest, servletResponse); is passing the request further, instead of returning a response.

You can read more about enabling CORS using Spring in Java here Enable CORS for OPTIONS request using Spring Framework

Sunday, December 5, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :