gpt4 book ai didi

java - 在自定义 spring boot 登录表单上显示错误登录消息

转载 作者:行者123 更新时间:2023-12-01 14:32:09 25 4
gpt4 key购买 nike

我正在开发自定义 Spring Boot 登录表单。当用户提供错误的凭据时,我希望我的应用程序重定向到同一页面并显示错误。我尝试的是创建我自己的 failureHandler 并在 onAuthenticationFailure 中将参数传递给请求。然后在我的登录 .jsp 表单中检查此参数是否存在并根据它显示错误,但它不起作用。我做错了什么?

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("ADMIN")
.antMatchers("/user/**")
.hasAnyRole("USER", "ADMIN")
.antMatchers("/guest*")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/guest/login")
.permitAll()
.defaultSuccessUrl("/user/all-tasks", true)
.failureUrl("/guest/login")
.failureHandler(new MyAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/user/logout")
.deleteCookies("JSESSIONID");
}
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
super.onAuthenticationFailure(request, response, exception);
request.setAttribute("error", true);
}
}
@Controller
@RequestMapping("/guest")
public class GuestController {
@GetMapping("/login")
public String login(){
return "login";
}
}
<div>
<c:if test="${error == true}">
<h1>DUPA</h1>
</c:if>
</div>

最佳答案

登录失败时。 Spring Security 将您发送回相同的登录页面,并带有特殊请求参数,例如 guest/login?error 或者您可以通过设置 .failureUrl() 将其更改为自定义你没有做的安全配置。

所以改成.failureUrl("/guest/login?error")

使用此 error 参数来识别使用 ${not empty param.error} 是否出现问题。

我猜您正在使用 JSP,并且 EL 默认可用。您可以在登录页面上添加类似下面的内容,这将为您提供失败的实际原因。

<c:if test="${not empty param.error}">
<p style="color:red">
Your login attempt was not
successful, try again.<br /> Reason: <c:out
value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />.
</p>
</c:if>

其中 SPRING_SECURITY_LAST_EXCEPTION 参数在 spring security 添加的用户 session 范围内可用,具有实际原因。

关于java - 在自定义 spring boot 登录表单上显示错误登录消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62163429/

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