angularjs - CORS problems with Spring-security -
i building app spring-boot (on http://localhost:8080) , angular (on http://localhost:80).
the frontend , backend code served 2 different servers. in order avoid cors problems, used put in place intermediate nginx server not satisfied solution anymore. hence, have allow cors.
i allowed cors globally lines :
@configuration public class webmvcconfiguration extends webmvcconfigureradapter { @override public void addcorsmappings(corsregistry registry) { registry.addmapping("/**") .allowedorigins("http://localhost") .allowcredentials(true) ; } }
this works every routes except authentication route handled spring security :
public class securityconfiguration extends websecurityconfigureradapter { @override public void configure(httpsecurity http) throws exception { http .formlogin() .successhandler(successhandler()) .failurehandler(failurehandler()) //[...] } private authenticationsuccesshandler successhandler() { return (httpservletrequest, httpservletresponse, authentication) -> httpservletresponse.setstatus(httpservletresponse.sc_ok); } private authenticationfailurehandler failurehandler() { return (httpservletrequest, httpservletresponse, e) -> { httpservletresponse.setstatus(httpservletresponse.sc_unauthorized); }; }
here code sends request on frontend part :
$http.post('http://localhost:8080/api/login', $.param({'username': username, 'password': password}), {headers: {'content-type': 'application/x-www-form-urlencoded'}} ).then(function() {}) .catch(function(error) {};
if enter correct password, http response code (that can see in chrome console) 200
still reach catch
block (with error.status = -1) , can see error message in console :
xmlhttprequest cannot load http://localhost:8080/api/login. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost' therefore not allowed access.
if enter wrong password reach catch block error message :
xmlhttprequest cannot load http://localhost:8080/api/login. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost' therefore not allowed access. response had http status code 401.
i notice cors response headers missing when call authentication endpoint.
any ideas?
edit : works if manually add headers in custom success handler. prefer if spring-security take account global cors configuration.
from experience you'll need include port number in cors, error message browser bit misleading.
you can verify inspecting network , check origin
field of request headers. value in access-control-allow-origin
of response headers must match including protocol , port.
Comments
Post a Comment