2012-09-02 66 views
7

如果当前请求是安全的,是否有办法“询问”spring security?因为即使我通过身份验证,我想检测我是否处于安全受保护的URL或匿名/公开页面Spring Security - 检查网址是否安全/受保护

在此先感谢!

+0

您的意思是请求包括intercept-url模式,或者它是通过身份验证的? – HRgiger

+0

我的意思是拦截URL模式和安全注释。 – user1641877

+0

我想测试我目前的请求是匿名还是已标记为使用配置或使用@Secured注释进行保护 – user1641877

回答

0

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

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

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

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

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

2

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 Dialect与Spring Security直接支持checking URL authorization。例如:

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

如果你的技术不支持直接进行检查,你可以方便地使用WebInvocationPrivilegeEvaluator(这是对象的JSP标签库和Thymeleaf使用)。例如,您可以@AutowireWebInvocationPrivilegeEvaluator的一个实例并直接使用它。很明显,语法会根据您使用它的地方(即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); 
} 
+0

这是对的,但它只适用于spring-security.xml中定义的URL模式(不适用于@PreAuthorize带注释的控制器方法),就像我前一段时间注意到的那样。你可以检查这个http://stackoverflow.com/questions/27984557/is-it-possible-to-know-if-a-url-is-accesible-when-using-spring-mvc-and-spring-se –

+0

当我不使用Spring Context时,如何获得此WebInvocationPrivilegeEvaluator? – Damian