Spring Security认证:用户名获得无SPRING_SECURITY_LAST_USERNAME [英] Spring security authentication: get username without SPRING_SECURITY_LAST_USERNAME
问题描述
我在春天框架新。我创建了我的web应用程序的登录页面,我希望用户对应用程序的任何行动之前登录。如果用户输入凭据好一切它的确定和工作,但如果进入坏的我想显示一条消息,并保持用户名输入元素上。显示一个消息是没有问题的,但我不能够保持用户名在我的JPS文件,而无需使用pcated变量SPRING_SECURITY_LAST_USERNAME去$ P $。
I'm new at spring framework. I'm creating a login page for my webapp and I want the user to login before any action on the app. If the user enters good credentials everything it's ok and working, but if enters bad ones I want to display a message and keep the username on the input element. Displaying a message is not a problem, but I'm not able to keep the username in my jps file without using the deprecated variable SPRING_SECURITY_LAST_USERNAME.
希望有人能帮助我,我使用Spring 3。
Hope someone can help me, I'm using Spring 3.
更新:要求说,我不希望显示的URL的用户名
UPDATE: the requirements says I don't want to display the username on the url.
推荐答案
去$ P $的文档pcated不断告诉你应该怎么做:
The documentation of the deprecated constant tells exactly what you should do:
/**
* @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>
在你的login.jsp:
In your login.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}"/>"/>
这篇关于Spring Security认证:用户名获得无SPRING_SECURITY_LAST_USERNAME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!