【发布时间】:2021-06-06 13:01:43
【问题描述】:
我 1 个月前开始学习 Spring,并且正在使用 Spring Security 做一些练习。当用户登录我的应用程序时,应用程序会检查凭据是否错误或是否启用了在我的帐户中注册的帐户;所以每个异常都有它的自定义消息。我的问题是自定义错误消息不显示,而只显示默认消息。我不知道问题出在哪里。这是代码:
自定义身份验证失败:
@Component
public class CustomAuthenticationFailure extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
setDefaultFailureUrl("/login.html?error=true");
super.onAuthenticationFailure(request, response, exception);
String errorMessage = "Bad Credentials";
if(exception.getClass().isAssignableFrom(DisabledException.class)) {
errorMessage = "User disabled";
} else if (exception.getMessage().equalsIgnoreCase("User account has expired")) {
errorMessage = "Account expired";
}
HttpSession session = request.getSession();
session.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
}
}
安全配置:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/signup/confirm-account").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login**").permitAll()
.failureUrl("/login?error=true")
.and()
.logout().permitAll();
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
login.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Login</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous"/>
<link rel="stylesheet" th:href="@{/css/main.css}"/>
</head>
<body>
<div class="container">
<div class="page-header clearfix">
<h1>CasaAgencyLogin!</h1>
</div>
<h2>Accedi</h2>
<div th:if="${param.error != null}"
th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}" class="alert alert-danger">
</div>
<div th:if="${param.logout}" class="alert alert-success">
Hai effettuato il logout. A presto!
</div>
<form th:action="@{/login}" method="post">
<div class="form-group"><label> Username: <input type="text" name="username" class="form-control"/> </label>
</div>
<div class="form-group"><label> Password: <input type="password" name="password" class="form-control"/> </label>
</div>
<div><input type="submit" value="Entra" class="btn btn-primary"/></div>
</form>
<footer class="login-footer">Non hai ancora un account? <a th:href="@{/signup}">Registrati!</a></footer>
</div>
</body>
</html>
【问题讨论】:
标签: java spring-boot spring-mvc spring-security thymeleaf