【问题标题】:Spring Security - check if web url is secure / protectedSpring Security - 检查 web url 是否安全/受保护
【发布时间】:2015-08-11 20:49:58
【问题描述】:

如果当前请求是安全的,有没有办法“询问”spring security?因为即使我通过了身份验证,我也想检测我是在安全受保护的 URL 中还是在匿名/公共页面中

提前致谢!

【问题讨论】:

  • 您的意思是请求包含拦截 URL 模式还是经过 ssl 身份验证?
  • 我的意思是拦截 URL 模式和安全注释。
  • 我想测试我当前的请求是匿名的还是使用配置或使用@Secured注解标记为安全的
  • 你在哪里可以解决这个问题?我也想知道请求 URL 是否应该受到保护。

标签: spring-security


【解决方案1】:

Spring Security 为此提供了JSP tag support。例如:

<sec:authorize url="/admin">

This content will only be visible to users who are authorized to access the "/admin" URL.

</sec:authorize>

Thymeleaf 提供了一个 Spring Security 方言,它直接支持 checking URL authorization 和 Spring Security。例如:

<div sec:authorize-url="/admin">
    This will only be displayed if authenticated user can call the "/admin" URL.
</div>

如果您的技术不支持直接执行检查,您可以轻松使用WebInvocationPrivilegeEvaluator(这是 JSP 标记库和 Thymeleaf 使用的对象)。例如,您可以@Autowire 一个WebInvocationPrivilegeEvaluator 的实例并直接使用它。显然,语法会根据您使用它的位置(即 GSP、Freemarker 等)而有所不同,但这里有一个直接使用 Java 代码的示例。

@Autowired
WebInvocationPrivilegeEvaluator webPrivs;

public void useIt() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    boolean hasAdminAccess = webPrivs.isAllowed("/admin", authentication);

    boolean hasAdminPostAccess = webPrivs.isAllowed(null, "/admin", "POST", authentication);
}

【讨论】:

  • 这是正确的,但它仅适用于 spring-security.xml 中定义的 url 模式(不适用于 @PreAuthorize 注释控制器方法),正如我前段时间注意到的那样。你可以检查这个stackoverflow.com/questions/27984557/…
  • 不使用Spring Context如何获取这个WebInvocationPrivilegeEvaluator?
【解决方案2】:

我认为您可以对AccessDecisionVoter 使用自己的实现,然后只需简单地覆盖Vote 方法并使用filterInvocation.getRequestUrl(); 方法比较拦截url。

@Override
public int vote(Authentication authentication, FilterInvocation filterInvocation,
    Collection<ConfigAttribute> attributes) {
  String requestUrl = filterInvocation.getRequestUrl();
  ....
}

【讨论】:

    【解决方案3】:

    我们可以将其标记为安全通道,因此转换为 https:// url。

        <intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" requires-channel="https" />
    

    然后我们可以使用 request.getScheme() 来识别它。 我使用了 org.springframework.security.version 3.1.4.RELEASE

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 2014-03-07
      • 2017-12-29
      • 2016-06-03
      • 2015-08-24
      • 2013-03-31
      • 2013-02-05
      • 2016-02-19
      相关资源
      最近更新 更多