如果当前请求是安全的,是否有方法"询问"spring安全性?因为即使我通过了身份验证,我也想检测我是在一个受安全保护的URL中还是在一个匿名/公共页面中
提前感谢!
Spring Security为此提供了JSP标记支持。例如:
<sec:authorize url="/admin">
This content will only be visible to users who are authorized to access the "/admin" URL.
</sec:authorize>
Thymelaf提供了一个Spring Security方言,它直接支持使用Spring Security检查URL授权。例如:
<div sec:authorize-url="/admin">
This will only be displayed if authenticated user can call the "/admin" URL.
</div>
如果您的技术不支持直接执行检查,则可以轻松使用WebInvocationPrivilegeEvaluator(这是JSP taglib和Thymelaf使用的对象)。例如,您可以将@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);
}
我认为您可以使用自己的AccessDecisionVoter
实现,然后只需覆盖Vote方法并使用filterInvocation.getRequestUrl();
方法比较截取url。
@Override
public int vote(Authentication authentication, FilterInvocation filterInvocation,
Collection<ConfigAttribute> attributes) {
String requestUrl = filterInvocation.getRequestUrl();
....
}
我们可以将其标记为安全通道,以便转换为https://url。
<intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" requires-channel="https" />
然后我们可以使用request.getScheme()来识别它。我使用了org.springframework.security.version.3.1.4.RELEASE