简体   繁体   中英

Displaying custom error messages in Spring Security?

I started to learn Spring 1 month ago and I'm doing some exercises with Spring Security. When a user logins into my app, the app check if the credentials are bad or less and if the account registered in my account is enabled; so every exception has its custom message. My problem is that the custom error message doesn't display but displays only the default message. I don't know where the problem is. This is the code:

CustomAuthenticationFailure:

@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);
    }

}

SecurityConfiguration:

@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>

You have to override the keys and their values in default “messages.properties” inside “spring-security-core.jar“.

For doing this, just write a properties file (say abcxyz.properties) for all/required keys and add a bean in your bean configuration file.

  <bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
        <value>abcxyz</value>
        </list>
    </property>
  </bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM