Add CorsFilter support

This commit is contained in:
Rob Winch
2016-07-05 14:24:28 -05:00
parent c935d857eb
commit 13bc70f693
13 changed files with 758 additions and 13 deletions

View File

@@ -17,20 +17,22 @@ package org.springframework.security.config.annotation;
import javax.servlet.Filter
import spock.lang.AutoCleanup
import spock.lang.Specification
import org.springframework.beans.factory.NoSuchBeanDefinitionException
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.mock.web.MockServletContext
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor;
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.context.SecurityContextHolder
@@ -40,11 +42,9 @@ import org.springframework.security.web.access.intercept.FilterSecurityIntercept
import org.springframework.security.web.context.HttpRequestResponseHolder
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
import org.springframework.security.web.csrf.CsrfToken
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository
import spock.lang.AutoCleanup
import spock.lang.Specification
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext
/**
*
@@ -88,7 +88,10 @@ abstract class BaseSpringSpec extends Specification {
}
def loadConfig(Class<?>... configs) {
context = new AnnotationConfigApplicationContext(configs)
context = new AnnotationConfigWebApplicationContext()
context.register(configs)
context.setServletContext(new MockServletContext())
context.refresh()
context
}

View File

@@ -0,0 +1,205 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers
import javax.servlet.http.HttpServletResponse
import org.springframework.context.annotation.Bean
import org.springframework.http.*
import org.springframework.security.config.annotation.BaseSpringSpec
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.web.bind.annotation.*
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
import org.springframework.web.servlet.config.annotation.EnableWebMvc
/**
*
* @author Rob Winch
*/
class CorsConfigurerTests extends BaseSpringSpec {
def "HandlerMappingIntrospector default"() {
setup:
loadConfig(DefaultCorsConfig)
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then:
responseHeaders == ['X-Content-Type-Options':'nosniff',
'X-Frame-Options':'DENY',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
'Expires' : '0',
'Pragma':'no-cache',
'X-XSS-Protection' : '1; mode=block']
}
@EnableWebSecurity
static class DefaultCorsConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors()
}
}
def "HandlerMappingIntrospector explicit"() {
setup:
loadConfig(MvcCorsConfig)
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setupWeb()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
@EnableWebMvc
@EnableWebSecurity
static class MvcCorsConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors()
}
@RestController
@CrossOrigin(methods = [
RequestMethod.GET, RequestMethod.POST
])
static class CorsController {
@RequestMapping("/")
String hello() {
"Hello"
}
}
}
def "CorsConfigurationSource"() {
setup:
loadConfig(ConfigSourceConfig)
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setupWeb()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
@EnableWebSecurity
static class ConfigSourceConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors()
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", new CorsConfiguration(allowedOrigins : ['*'], allowedMethods : [
RequestMethod.GET.name(),
RequestMethod.POST.name()
]))
source
}
}
def "CorsFilter"() {
setup:
loadConfig(CorsFilterConfig)
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setupWeb()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
@EnableWebSecurity
static class CorsFilterConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.cors()
}
@Bean
CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", new CorsConfiguration(allowedOrigins : ['*'], allowedMethods : [
RequestMethod.GET.name(),
RequestMethod.POST.name()
]))
new CorsFilter(source)
}
}
def addCors(boolean isPreflight=false) {
request.addHeader(HttpHeaders.ORIGIN,"https://example.com")
if(!isPreflight) {
return
}
request.method = HttpMethod.OPTIONS.name()
request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
}
}

View File

@@ -0,0 +1,176 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.config.http
import javax.servlet.http.HttpServletResponse
import org.springframework.http.*
import org.springframework.mock.web.*
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint
import org.springframework.web.bind.annotation.*
import org.springframework.web.filter.CorsFilter
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
/**
*
* @author Rob Winch
* @author Tim Ysewyn
*/
class HttpCorsConfigTests extends AbstractHttpConfigTests {
MockHttpServletRequest request
MockHttpServletResponse response
MockFilterChain chain
def setup() {
request = new MockHttpServletRequest(method:"GET")
response = new MockHttpServletResponse()
chain = new MockFilterChain()
}
def "HandlerMappingIntrospector default"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'()
'intercept-url'(pattern:'/**', access: 'authenticated')
}
bean('ep', Http403ForbiddenEntryPoint)
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then:
responseHeaders == ['X-Content-Type-Options':'nosniff',
'X-Frame-Options':'DENY',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
'Expires' : '0',
'Pragma':'no-cache',
'X-XSS-Protection' : '1; mode=block']
}
def "HandlerMappingIntrospector explicit"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'()
'intercept-url'(pattern:'/**', access: 'authenticated')
}
bean('ep', Http403ForbiddenEntryPoint)
bean('controller', CorsController)
xml.'mvc:annotation-driven'()
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setup()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
def "CorsConfigurationSource"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'('configuration-source-ref':'ccs')
'intercept-url'(pattern:'/**', access: 'authenticated')
}
bean('ep', Http403ForbiddenEntryPoint)
bean('ccs', MyCorsConfigurationSource)
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setup()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
def "CorsFilter"() {
setup:
xml.http('entry-point-ref' : 'ep') {
'cors'('ref' : 'cf')
'intercept-url'(pattern:'/**', access: 'authenticated')
}
xml.'b:bean'(id: 'cf', 'class': CorsFilter.name) {
'b:constructor-arg'(ref: 'ccs')
}
bean('ep', Http403ForbiddenEntryPoint)
bean('ccs', MyCorsConfigurationSource)
createAppContext()
when:
addCors()
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
when:
setup()
addCors(true)
springSecurityFilterChain.doFilter(request,response,chain)
then: 'Ensure we a CORS response w/ Spring Security headers too'
responseHeaders['Access-Control-Allow-Origin']
responseHeaders['X-Content-Type-Options']
response.status == HttpServletResponse.SC_OK
}
def addCors(boolean isPreflight=false) {
request.addHeader(HttpHeaders.ORIGIN,"https://example.com")
if(!isPreflight) {
return
}
request.method = HttpMethod.OPTIONS.name()
request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
}
def getResponseHeaders() {
def headers = [:]
response.headerNames.each { name ->
headers.put(name, response.getHeaderValues(name).join(','))
}
return headers
}
@RestController
@CrossOrigin(methods = [
RequestMethod.GET, RequestMethod.POST
])
static class CorsController {
@RequestMapping("/")
String hello() {
"Hello"
}
}
static class MyCorsConfigurationSource extends UrlBasedCorsConfigurationSource {
MyCorsConfigurationSource() {
registerCorsConfiguration('/**', new CorsConfiguration(allowedOrigins : ['*'], allowedMethods : [
RequestMethod.GET.name(),
RequestMethod.POST.name()
]))
}
}
}