Java 禁用 OPTIONS Http 方法的 Spring Security
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21696592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable Spring Security for OPTIONS Http Method
提问by Dhanush Gopinath
Is it possible to disable Spring Security for a type of HTTP Method?
是否可以为一种 HTTP 方法禁用 Spring Security?
We have a Spring REST application with services that require Authorization token to be attached in the header of http request. I am writing a JS client for it and using JQuery to send the GET/POST requests. The application is CORS enabled with this filter code.
我们有一个 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());
}
But when JQuery sends in the OPTIONS request for CORS, the server responds with Authorization Failed token. Clearly the OPTIONS request, lacks Authorization token. So is it possible to let the OPTIONS escape the Security Layer from the Spring Security Configuration?
但是当 JQuery 发送 CORS 的 OPTIONS 请求时,服务器会以 Authorization Failed 令牌响应。显然 OPTIONS 请求缺少授权令牌。那么是否有可能让 OPTIONS 从 Spring Security Configuration 中逃脱安全层?
采纳答案by Koitoer
Have you tried this
你有没有试过这个
You can use multiple elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top. You can also add a method attribute to limit the match to a particular HTTP method (GET, POST, PUT etc.).
您可以使用多个元素为不同的 URL 集定义不同的访问要求,但它们将按照列出的顺序进行评估,并使用第一个匹配项。因此,您必须将最具体的匹配项放在顶部。您还可以添加一个方法属性来限制与特定 HTTP 方法(GET、POST、PUT 等)的匹配。
<http auto-config="true">
<intercept-url pattern="/client/edit" access="isAuthenticated" method="GET" />
<intercept-url pattern="/client/edit" access="hasRole('EDITOR')" method="POST" />
</http>
Above means you need to select the url pattern to intercept and what methods you want
上面的意思是你需要选择拦截的url模式和你想要的方法
回答by Felby
If you're using an annotation based security config file (@EnableWebSecurity
& @Configuration
) you can do something like the following in the configure()
method to allow for the OPTION
requests to be permitted by Spring Security without authentication for a given path:
如果您使用的是基于注解的安全配置文件 ( @EnableWebSecurity
& @Configuration
),您可以在configure()
方法中执行类似以下操作,以允许OPTION
Spring Security 允许请求,而无需对给定路径进行身份验证:
@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();
}
回答by Luc S.
Allow all OPTIONS in context:
在上下文中允许所有选项:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
回答by Dennis Kieselhorst
In case someone is looking for an easy solution using Spring Boot. Just add an additional bean:
如果有人正在寻找使用 Spring Boot 的简单解决方案。只需添加一个额外的bean:
@Bean
public IgnoredRequestCustomizer optionsIgnoredRequestsCustomizer() {
return configurer -> {
List<RequestMatcher> matchers = new ArrayList<>();
matchers.add(new AntPathRequestMatcher("/**", "OPTIONS"));
configurer.requestMatchers(new OrRequestMatcher(matchers));
};
}
Please note that depending on your application this may open it for potential exploits.
请注意,根据您的应用程序,这可能会打开它以进行潜在的攻击。
Opened issue for a better solution: https://github.com/spring-projects/spring-security/issues/4448
打开问题以获得更好的解决方案:https: //github.com/spring-projects/spring-security/issues/4448
回答by FabianoLothor
In some cases, it is needed add configuration.setAllowedHeaders(Arrays.asList("Content-Type"));
to corsConfigurationSource()
when using WebSecurityConfigurerAdapter
to solve the cors problem.
在某些情况下,必要时添加configuration.setAllowedHeaders(Arrays.asList("Content-Type"));
到corsConfigurationSource()
用时WebSecurityConfigurerAdapter
解决CORS问题。
回答by Meysam
If you're using annotation-based security config then you should add spring's CorsFilter
to the application context by calling .cors()
in your config, something like this:
如果您使用的是基于注解的安全配置,那么您应该CorsFilter
通过调用.cors()
您的配置将 spring 的添加到应用程序上下文中,如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.cors();
}