2013-02-24 94 views
10

我是春季框架的新手。我爲我的webapp創建了一個登錄頁面,我希望用戶在應用程序的任何操作之前登錄。如果用戶輸入了良好的憑據,那麼它就可以正常工作了,但是如果輸入錯誤的憑據,我想顯示一條消息並在輸入元素上保留用戶名。顯示消息不是問題,但我無法在不使用棄用變量SPRING_SECURITY_LAST_USERNAME的情況下將用戶名保留在我的jps文件中。春季安全認證:獲取用戶名無SPRING_SECURITY_LAST_USERNAME

希望有人能幫助我,我用彈簧3

UPDATE:要求說我不想顯示的URL的用戶名。

回答

22

棄用常量的文檔準確地告訴你應該做的:

/** 
* @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler} 
*/ 
@Deprecated 
public static final String SPRING_SECURITY_LAST_USERNAME_KEY = 
      "SPRING_SECURITY_LAST_USERNAME"; 

事情是這樣的:

public class UserNameCachingAuthenticationFailureHandler 
    extends SimpleUrlAuthenticationFailureHandler { 

    public static final String LAST_USERNAME_KEY = "LAST_USERNAME"; 

    @Autowired 
    private UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter; 

    @Override 
    public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, 
      AuthenticationException exception) 
      throws IOException, ServletException { 

     super.onAuthenticationFailure(request, response, exception); 

     String usernameParameter = 
      usernamePasswordAuthenticationFilter.getUsernameParameter(); 
     String lastUserName = request.getParameter(usernameParameter); 

     HttpSession session = request.getSession(false); 
     if (session != null || isAllowSessionCreation()) { 
      request.getSession().setAttribute(LAST_USERNAME_KEY, lastUserName); 
     } 
    } 
} 

在您的安全配置:

<security:http ...> 
    ... 
    <security:form-login 
     authentication-failure-handler-ref="userNameCachingAuthenticationFailureHandler" 
    ... 
    /> 
</security:http> 

<bean 
    id="userNameCachingAuthenticationFailureHandler" 
    class="so.UserNameCachingAuthenticationFailureHandler"> 
    <property name="defaultFailureUrl" value="/url/to/login?error=true"/> 
</bean> 

在登錄.jsp:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ page session="true" %> 

... 

<%--in the login form definition--%> 
<input id="j_username" name="j_username" type="text" 
    value="<c:out value="${sessionScope.LAST_USERNAME}"/>"/> 
+0

非常感謝!它像需要的那樣工作! – droidpl 2013-02-24 16:21:58

+1

沒問題。請注意,有些地方還有改進空間。例如。在.jsp中對會話屬性的名稱進行硬編碼並不優雅。理想情況下,它應該引用在'UserNameCachingAuthenticationFailureHandler'中定義的常量。 (我不得不讚嘆我不知道如何實現這種間接。) – zagyi 2013-02-24 16:27:21

+0

我不知道這可以實現!但現在這就是我所需要的,這不是安全性,而是讓用戶生活更美好的一個小訣竅!我不可能在任何地方找到另一種簡單的解決方案,這是不可思議的! ;) – droidpl 2013-02-24 16:43:33

4

如果有人在這裏遇到了Grails Spring安全性問題。您現在可以使用以下各項

import grails.plugin.springsecurity.SpringSecurityUtils; 

現在使用SpringSecurityUtils.SPRING_SECURITY_LAST_USERNAME_KEY這將工作,不會被棄用。