2012-10-29 57 views
22

我是新來的彈簧:彈簧安全 - 重定向如果已經登錄

我不希望經過身份驗證的用戶訪問登錄頁面。如果用戶已經通過身份驗證,處理'/ login'重定向的正確方法是什麼?說,如果已經登錄,我想重定向到'/ index'。

我嘗試過在登錄時使用'isAnonomous()',但它重定向到訪問被拒絕的頁面。

<security:http auto-config="true" use-expressions="true" ...> 
    <form-login login-processing-url="/resources/j_spring_security_check" 
       default-target-url="/index" 
       login-page="/login" authentication-failure-url="/login?login_error=t" /> 
    <logout logout-url="/resources/j_spring_security_logout" /> 
    ... 
    <security:intercept-url pattern="/login" access="permitAll" /> 
    <security:intercept-url pattern="/**" access="isAuthenticated()" /> 
</security:http> 
+0

可能重複[如果用戶在登錄後訪問登錄頁面,如何重定向到主頁?](http://stackoverflow.com/questions/12597519/how-to-redirect-to-the-homepage -if-the-user-access-the-login-page-after-being) – Xaerxess

+0

http://stackoverflow.com/questions/32225414/spring-security-login-issue-after-re-login-in-same-會話/ 32325358#32325358 此問題已在此鏈接上解決。請查看 – parshant

回答

35

在登錄頁面的控制器功能:

  1. 檢查,如果用戶登錄

  2. 再往前他索引頁在這種情況下。

相關代碼:

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 

if (!(auth instanceof AnonymousAuthenticationToken)) { 

    /* The user is logged in :) */ 
    return new ModelAndView("forward:/index"); 
} 
+4

這隻適用於登錄 - >家庭等情況。如果我已經登錄並在地址欄中輸入登錄網址,怎麼辦?這將是有道理的重新導向到主頁(或我已經在哪裏)... –

+0

它爲我工作。謝謝 – zameer

0

嘿,你能做到這一點。

<h:head> 
<sec:authorize access="isAuthenticated()"> 
    <meta http-equiv="refresh" content="0;url=http://your index.xhtml url (full url)" /> 
</sec:authorize> 
</h:head> 

這種方法非常簡單方便,不是嗎?

1

login.xhtml

<h:head > 
    <f:metadata> 
     <f:event type="preRenderView" listener="#{loginBean.onPageLoad}"/> 
    </f:metadata> 
</h:head> 

loginBean

public void onPageLoad(){ 
    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
    if (!(auth instanceof AnonymousAuthenticationToken)) { 
     try { 
      FacesContext.getCurrentInstance().getExternalContext().redirect(url); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
5

要成功地從登錄頁面重定向,如果用戶已經登錄,添加以下到您的login.jsp:

添加一個安全的taglib頭部到您的jsp頂部:

<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%> 

然後添加以下標記你的「頭」標籤內(最好是靠近頂部):

<sec:authorize access="isAuthenticated()"> 
    <% response.sendRedirect("main"); %> 
</sec:authorize> 

這將重定向到main.html中(或任何你的主要的.jsp映射到),如果用戶訪問登錄頁面已經登錄。

通過控制器做到這一點並不適合我,因爲有效的登錄頁面的做法是讓spring security的「表單登錄」bean完成所有的重定向工作,所以沒有登錄控制器可以修改。