2013-02-24 3 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

+1

問題ありません。いくつかの点で改善の余地があることに注意してください。例えば。 .jsp内のセッション属性の名前をハードコードするのはエレガントではありません。理想的には、 'UserNameCachingAuthenticationFailureHandler'で定義された定数を参照するべきです。 (私はこのインダイレクションを達成する方法がわからないことに気付かなければならない) – zagyi

+0

これは達成できるかどうかわからなかった!しかし、今はそれが私が必要とするすべてのものです。これはセキュリティではなく、ユーザーの生活をより良くするための小さなトリックです。私はこのような別の簡単な解決策を見つけることができないと信じられないほどです! ;) – droidpl

4

Grails Springのセキュリティで誰かがこの問題を抱えている場合は、あなたは今following-

import grails.plugin.springsecurity.SpringSecurityUtils; 

は今、これが機能し、廃止予定されていないSpringSecurityUtils.SPRING_SECURITY_LAST_USERNAME_KEYを使用することができます。

関連する問題