在 Spring Security 中显示自定义错误消息?

时间:2021-03-08 16:16:36

标签: java spring-boot spring-mvc spring-security thymeleaf

我在 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();
    }
}

登录.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 个答案:

答案 0 :(得分:0)

您必须在“spring-security-core.jar”中的默认“messages.properties”中覆盖键及其值。

为此,只需为所有/必需的键编写一个属性文件(例如 abcxyz.properties)并在您的 bean 配置文件中添加一个 bean。

import
相关问题