为 OPTIONS Http 方法禁用 Spring Security [英] Disable Spring Security for OPTIONS Http Method

查看:39
本文介绍了为 OPTIONS Http 方法禁用 Spring Security的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为某种类型的 HTTP 方法禁用 Spring Security?

Is it possible to disable Spring Security for a type of HTTP Method?

我们有一个 Spring REST 应用程序,其服务需要在 http 请求的标头中附加授权令牌.我正在为它编写一个 JS 客户端并使用 JQuery 发送 GET/POST 请求.应用程序启用了此过滤器代码的 CORS.

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.

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 请求缺少授权令牌.那么有没有可能让OPTIONS从Spring安全配置中脱离安全层?

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?

推荐答案

你试过了吗

您可以使用多个元素来定义不同的不同 URL 集的访问要求,但它们将是按列出的顺序评估,将使用第一个匹配项.那么你必须将最具体的匹配项放在顶部.您还可以添加一个method 属性将匹配限制为特定的 HTTP 方法(GET、POST、PUT 等).

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.).

<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模式和你想要的方法

Above means you need to select the url pattern to intercept and what methods you want

这篇关于为 OPTIONS Http 方法禁用 Spring Security的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆