在 Spring Security 中显示自定义错误消息?
Posted
技术标签:
【中文标题】在 Spring Security 中显示自定义错误消息?【英文标题】:Displaying custom error messages in Spring Security? 【发布时间】: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>
【问题讨论】:
【参考方案1】:您必须覆盖“spring-security-core.jar”中默认“messages.properties”中的键及其值。
为此,只需为所有/必需的键编写一个属性文件(比如 abcxyz.properties),然后在 bean 配置文件中添加一个 bean。
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>abcxyz</value>
</list>
</property>
</bean>
【讨论】:
对不起,你能说得更详细一点吗? 您应该找到存储了以上是关于在 Spring Security 中显示自定义错误消息?的主要内容,如果未能解决你的问题,请参考以下文章
如何在jsp中为spring security auth异常显示自定义错误消息
Spring Security 自定义 AuthenticationException 消息
Spring Security:来自 UserDetailsService 的自定义异常消息
java - spring security自定义tomcat错误页面