【问题标题】:Displaying custom error messages in Spring Security?在 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>

【问题讨论】:

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


    【解决方案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 默认类。让您的 abcxyz 文件具有相同的 KEY 和本地化 MESSAGE。在您的示例中,您刚刚更新了 Java 代码,而不是 Spring Security 使用的消息包。因此,您必须使用 bean 更新您的应用程序上下文,覆盖默认消息的使用。如果您想以自己的方式实现auth接口并处理显示的异常here,还有另一种方法
    • 我会照你说的做,但没有,这是代码stackoverflow.com/questions/66548054/…
    猜你喜欢
    • 2017-05-15
    • 2014-01-01
    • 2010-11-25
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多