2012-09-02 67 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