2011-09-21 26 views
2

我有一個典型的Spring MVC + GWT體系結構,並且Apache Shiro是一個安全層。當@Controller重定向到登錄頁面時如何配置Shiro + Spring MVC

問題: 無論使用什麼協議向App服務器發送請求,頁面都應該以請求的「X-Forwarded-Proto」頭中指定的協議返回(所以應用服務器可以接收HTTP請求,但如果標題顯示HTTPS,則應使用HTTPS進行響應)。

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 
    <property name="securityManager" ref="securityManager"/> 
    <property name="loginUrl" value="/login.jsp"/> 
    <property name="filterChainDefinitions"> 
    <value> 
     /** = authc 
    </value> 
    </property> 
</bean> 

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 
    <property name="realm" ref="myRealm"/> 
</bean> 

<bean id="myRealm" class="com.myapp.security.DBRealm"> 
    <property name="credentialsMatcher" ref="sha256Matcher"/> 
</bean> 

可能的解決辦法:

顯然,在四郎彈簧教程中指定的配置將無法正常工作,因爲它沒有任何與協議(login.jsp的使用將在請求中使用的協議退還)

使用@Controller重定向到與指定的協議登錄視圖:

@RequestMapping(value="/login", method=RequestMethod.GET) 
public RedirectView doLogin(HttpServletRequest req) throws MalformedURLException { 
    URL originalURL = new URL(req.getRequestURL().toString()); 
    return new RedirectView(new URL(req.getHeader("X-Forwarded-Proto"), originalURL.getHost(), "/login.jsp").toString()); 
} 

和更改loginUrl在四郎配置爲指向/登錄,以便@Controller捕獲它:

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 
    <property name="securityManager" ref="securityManager"/> 
    <property name="loginUrl" value="/login"/> 
    ... leave everything else the same 
</bean> 

但有了這個配置,雖然我得到相同的登錄頁面,則MYREALM(com.myapp.security.DBRealm)完全不觸發(意思是,憑據沒有檢查),並登錄總是失敗。看起來像重定向頁面失去了「掛鉤」的領域。

關於我在做什麼的錯誤?

回答

3

這是失敗的原因是因爲Shiro authc篩選器(a FormAuthenticationFilter)預計loginUrl是發生登錄嘗試的那個。

也就是說,當authc過濾與loginUrl匹配的請求時,它將自動支持基於表單的身份驗證。由於您正在將最終用戶重定向至與loginUrl(即loginUrl = /login,但您將其重定向至/login.jsp)不匹配的網址,因此authc過濾器將不會執行登錄。

你最好的選擇IMO:

子類FormAuthenticationFilter並重寫redirectToLogin方法來使用你的X-Forwarded-Proto邏輯。然後重新定義'authc'爲您的自定義子類。例如,使用四郎的.ini:

[main] 
    ... 
    authc = com.foo.my.FormAuthenticationFilterSubclass 

另外,如果要直接在四郎這種行爲(因此四郎查找執行默認重定向時頭),這樣你可以刪除你的子類,請打開功能請求Apache Shiro's Jira

+0

謝謝,Les。我會嘗試的。讓Shiro「本地」支持X-Forwarded-Proto可能不是最有用的功能(不知道有多少人有類似的情況),但能夠設置單獨的URL - 一個用於「redirectToLoginURL」,另一個用於「performAuthenticationURL (s)「 - 可能真的有幫助。 – Djam

相關問題