gpt4 book ai didi

Spring安全认证: get username without SPRING_SECURITY_LAST_USERNAME

转载 作者:IT老高 更新时间:2023-10-28 13:48:04 29 4
gpt4 key购买 nike

我是 Spring 框架的新手。我正在为我的 web 应用程序创建一个登录页面,并且我希望用户在对应用程序进行任何操作之前登录。如果用户输入了良好的凭据,一切都可以正常工作,但是如果输入错误的凭据,我想显示一条消息并将用户名保留在输入元素上。显示消息不是问题,但如果不使用已弃用的变量 SPRING_SECURITY_LAST_USERNAME,我无法将用户名保留在我的 jps 文件中。

希望有人可以帮助我,我正在使用 Spring 3。

更新:要求说我不想在 url 上显示用户名。

最佳答案

已弃用常量的文档准确地说明了您应该做什么:

/**
* @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 中:

<%@ 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安全认证: get username without SPRING_SECURITY_LAST_USERNAME,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15052860/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com