2011-09-27 50 views
8

假設我有一個簡單的頁面,名爲faq.html。我希望這個頁面可以公開訪問,所以我申請通常春季安全配置:檢索Spring Security的身份驗證,即使在filter =「none」的公共頁面上。

<sec:intercept-url pattern="/faq.html" filters="none" /> 

讓我們也說,如果用戶進行身份驗證之後到達這個頁面,我想打印「喜姓」頁面上。對於需要身份驗證的網頁,我只是把the result of the following到我ModelMap,然後名字都可以訪問在我看來以後:

SecurityContextHolder.getContext().getAuthentication().getPrincipal() 

這並不適用於faq.html工作,大概是因爲當你指定filters="none",則調用到getPrincipal()返回null。 (這種行爲很有道理,因爲配置會導致應用沒有過濾器)。所以,相反,它似乎是我必須做手工一堆Spring Security的東西:

public static Authentication authenticate(HttpServletRequest request, 
     HttpServletResponse response, SecurityContextRepository repo, 
     RememberMeServices rememberMeServices) { 
    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 

    // try to load a previous Authentication from the repository 
    if (auth == null) { 
     SecurityContext context = repo.loadContext(
       new HttpRequestResponseHolder(request, response)); 
     auth = context.getAuthentication(); 
    } 

    // check for remember-me token 
    if (auth == null) { 
     auth = rememberMeServices.autoLogin(request, response); 
    } 

    return auth; 
} 

有沒有更好的方式來做到這一點?例如,Spring似乎應該提供一些工具,通過原始的<sec:intercept-url />配置來掛接它們的API調用。

+0

請注意,'filters =「none」'似乎在Spring 3.1.0中已被棄用:http://stackoverflow.com/a/5382178/521799 –

回答

11

這就是不使用filters = "none"作爲公共頁面的原因。

改爲使用access = "permitAll"(或access = "IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED",如果您沒有use-expressions = "true")。

+0

Rock on。我不知道這個選擇。 – jtoberon

相關問題