Asked  8 Months ago    Answers:  5   Viewed   12 times

i have implemented filter for cors in spring boot.the code is as follow:-

@springbootapplication
@component
public class application implements filter {
public static void main(string[] args) {
    springapplication.run(application.class, args);
}

@override
public void init(filterconfig filterconfig) throws servletexception {

}

@override
public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception {
    httpservletrequest request = (httpservletrequest) servletrequest;
    httpservletresponse response = (httpservletresponse) servletresponse;

    response.setheader("access-control-allow-origin", "*");
    response.setheader("access-control-allow-credentials", "true");
    response.setheader("access-control-allow-methods", "post, get, options, delete");
    response.setheader("access-control-max-age", "3600");
    response.setheader("access-control-allow-headers", "content-type, accept, x-requested-with, remember-me");

    filterchain.dofilter(servletrequest, servletresponse);
}

@override
public void destroy() {

}
}

to get the access_token from oauth2 i have created following object from angularjs:-

 {"url":"http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=clientid&client_secret=clientsecret","headers":{"authorization":"basic token_value"},"withcredentials":true,"method":"post"}

i am getting following error when i hit the server:-

options url... 401() response for preflight has invalid http status code 401

i have looked for the solutions for similar problems in but none of them fixed my problem.could someone please help on this?

 Answers

4

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
 
1

avoid filtering and set status 200 when http method is options

if("options".equalsignorecase(request.getmethod())) {
    response.setstatus(httpservletresponse.sc_ok);
} else {
    chain.dofilter(req, res);
}
Friday, June 25, 2021
 
LukeP
 
4

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

<httpprotocol>
  <customheaders>
    <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" />
  </customheaders>
</httpprotocol>

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;
            config.formatters.remove(config.formatters.xmlformatter);

            config.enablecors(enablecorsattribute);

and controller looks like this.

[enablecors(origins: "*", headers: "*", methods: "*", supportscredentials = true)]
    [routeprefix("api/add_client_")]
    public class add_client_controller : apicontroller
    {
[acceptverbs("post")]

        [httppost]
        [route("postgoals")]
        public string postgoals(string goal)
        {
            goal g = new goal();
            g.goals = goal;
            db.goals.add(g);
            int res = db.savechanges();

            return ("success");
        }
}

and angular post method looks like following

 save_goals(){

  let headers : headers= new headers();
        headers.append('content-type','application/x-www-form-urlencoded');
    headers.append('access-control-allow-origin','*');
      headers.append('access-control-allow-methods','get,put,post,delete');
      headers.append('access-control-allow-headers','content-type');

      let options = new requestoptions({ headers: headers });
    return this._http.post('http://localhost:49975/api/add_client_/postgoals?goal=check',options)
       .map(res =>  res.json());
    }

this is work around to send data with url.

Friday, July 30, 2021
 
4

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.

 app.usecors(corsoptions.allowall);

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
 
3

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.post = {};
  $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: http://www.html5rocks.com/en/tutorials/cors/

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
 
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 :