Description
Using Spring Boot in combination with Spring Security and enabling Cors Support with Annotation @crossorigin leads to a broken cors response if the authentication with spring security fails.
Considering java script code for cors request:
url = 'http://localhost:5000/api/token'
xmlhttp = new XMLHttpRequest
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState is 4
console.log xmlhttp.status
xmlhttp.open "GET", url, true
# xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
do xmlhttp.send
The output needs to be 200. If the credentials are valid, the request will be 200.
Considering the usecase the credentials are wrong, you would expect output 401 (the standard code for failed authentication). but with spring boot and spring security the output will be 0 with the browser notification:
XMLHttpRequest cannot load http://localhost:5000/api/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://rudolfschmidt:3000' is therefore not allowed access. The response had HTTP status code 401.
The OPTION request goes through
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:5000
Origin:http://localhost:3000
Pragma:no-cache
Referer:http://localhost:3000/
and the reserver response
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:authorization
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:http://localhost:3000
Access-Control-Max-Age:1800
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Mon, 02 May 2016 06:52:03 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
and the result is
Request URL:http://localhost:5000/api/token
Request Method:OPTIONS
Status Code:200 OK
Remote Address:[::1]:5000
everthing is fine.
but now the real request starts:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Authorization:Basic YTphYQ==
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:5000
Origin:http://localhost:3000
Pragma:no-cache
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36
and the response is
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Mon, 02 May 2016 06:52:03 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
WWW-Authenticate:Basic realm="Realm"
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
the result is
Request URL:http://localhost:5000/api/token
Request Method:GET
Status Code:401 Unauthorized
Remote Address:[::1]:5000
its also fine, but because the failing header Access-Control-Allow-Origin the ajax request is broken.
I assume that spring security doesnt notice that corsSupport is enabled, because the CrossOrigin Annotiation is at the RestController. Spring Security handles like a gateway before the request has a chance to reach the Annotation that enables the Cors Headers.
The solution is adding a CorsFilter in the Spring Security Chan.
My Spring Code
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
@RequestMapping("api")
public class Controller {
@RequestMapping("token")
@CrossOrigin
Map<String, String> token(HttpSession session) {
return Collections.singletonMap("token", session.getId());
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
PasswordEncoder passwordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.requestMatchers(CorsUtils::isCorsRequest).permitAll()
.anyRequest().authenticated()
.and().httpBasic()
.and().addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class);
}
}
public class WebSecurityCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, x-requested-with, Cache-Control");
chain.doFilter(request, res);
}
@Override
public void destroy() {
}
}
The solution works but the external filter is ugly and should be work out of the box.
I hope spring boot is the right repository for that issue cause it refers to spring security as well.