2013-02-24 42 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这将工作,不会被弃用。