是否可以禁用某种HTTP方法的Spring Security?
我们有一个Spring REST应用程序,其服务要求授权令牌附加到http请求的标头中。我正在为它编写一个JS客户端,并使用JQuery发送GET/POST请求。应用程序使用此筛选器代码启用 CORS。
doFilter(....) {
HttpServletResponse httpResp = (HttpServletResponse) response;
httpResp.setHeader("Access-Control-Allow-Origin", "*");
httpResp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpResp.setHeader("Access-Control-Max-Age", "3600");
Enumeration<String> headersEnum = ((HttpServletRequest) request).getHeaders("Access-Control-Request-Headers");
StringBuilder headers = new StringBuilder();
String delim = "";
while (headersEnum.hasMoreElements()) {
headers.append(delim).append(headersEnum.nextElement());
delim = ", ";
}
httpResp.setHeader("Access-Control-Allow-Headers", headers.toString());
}
但是当 JQuery 发送 CORS 的 OPTIONS 请求时,服务器会使用授权失败令牌进行响应。显然,选项请求缺少授权令牌。那么,是否可以让 OPTIONS 从 Spring 安全配置中转义安全层呢?
如果您使用的是基于注释的安全配置文件(@EnableWebSecurity
& @Configuration
),则可以在 configure()
方法中执行以下操作,以允许 Spring Security 允许 OPTION
请求,而无需对给定路径进行身份验证:
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
允许上下文中的所有选项:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
你试过这个吗
您可以使用多个元素来定义不同的 不同 URL 集的访问要求,但它们将是 按列出的顺序进行评估,将使用第一个匹配项。所以你 必须将最具体的匹配项放在顶部。您还可以添加 方法属性,用于限制与特定 HTTP 方法的匹配(GET, 发布、放置等)。
<http auto-config="true">
<intercept-url pattern="/client/edit" access="isAuthenticated" method="GET" />
<intercept-url pattern="/client/edit" access="hasRole('EDITOR')" method="POST" />
</http>
以上意味着您需要选择要拦截的 url 模式以及您想要的方法
不建议使用接受的答案,您不应该这样做.
以下是Spring Security和jQuery的ajax的CORS设置的正确方法。
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(userAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors() // <-- This let it use "corsConfigurationSource" bean.
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
...
}
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
// NOTE: setAllowCredentials(true) is important,
// otherwise, the value of the 'Access-Control-Allow-Origin' header in the response
// must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// NOTE: setAllowedHeaders is important!
// Without it, OPTIONS preflight request will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(Arrays.asList(
"Authorization",
"Accept",
"Cache-Control",
"Content-Type",
"Origin",
"x-csrf-token",
"x-requested-with"
));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
从jQuery方面来看。
$.ajaxSetup({
// NOTE: Necessary for CORS
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
如果有人正在寻找使用Spring Boot的简单解决方案。只需添加一个额外的 bean:
@Bean
public IgnoredRequestCustomizer optionsIgnoredRequestsCustomizer() {
return configurer -> {
List<RequestMatcher> matchers = new ArrayList<>();
matchers.add(new AntPathRequestMatcher("/**", "OPTIONS"));
configurer.requestMatchers(new OrRequestMatcher(matchers));
};
}
请注意,根据您的应用程序,这可能会打开它以供潜在攻击。
更好的解决方案的开放问题:https://github.com/spring-projects/spring-security/issues/4448
如果您使用的是基于注释的安全配置,那么您应该通过在配置中调用 .cors()
将 Spring 的CorsFilter
添加到应用程序上下文中,如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.cors();
}
在某些情况下,使用 WebSecurityConfigurerAdapter
解决 cors 问题时需要将configuration.setAllowedHeaders(Arrays.asList("Content-Type"));
添加到corsConfigurationSource()
。