How to send an error message to view

Asked

Viewed 643 times

4

I am a little lost here, I would like to put a parameter in the view to inform the user that his password is wrong, expired etc. the problem that spring-security identifies.

Websecurityconfigureradapter

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsRepository userDetailsRepository;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/home", "/").authenticated()
                .antMatchers("/admin/**").access("hasRole('ADMIN')")
                .and().formLogin().loginPage("/login")
                .usernameParameter("login").passwordParameter("pass")
                .and().csrf().disable()
                .exceptionHandling()
                .accessDeniedHandler(new AuthAcessDeniedHandler() {
                }).accessDeniedPage("/login?error");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsRepository)
                .passwordEncoder(new BCryptPasswordEncoder());
    }


}

Accessdeniedhandler

public class AuthAcessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // Gostaria de colocar esse parâmetro na VIEW
        request.setAttribute("error","Login invalido");

    }
}

View (freemaker)

  $(document).ready(function () {
        /*
         * JS login effect
         * This script will enable effects for the login page
         */

        // Elements

    alert('${(Request.error)!"John Doe"}');
    ..........etc

accessDeniedHandler(new AuthAcessDeniedHandler() ) never runs!

2 answers

4


Solution, there is a method in the DSL call dedicated to this "hook"

Securityconfiguration

   http.authorizeRequests()
                    .antMatchers("/home", "/").authenticated()
                    .antMatchers("/admin/").access("hasRole('ADMIN')")
                    .and().formLogin().failureHandler(new CustomfailureHandler())
                    .loginPage("/login")
                    .usernameParameter("login").passwordParameter("pass")
                    .and()
                    .exceptionHandling().accessDeniedPage("/login?error");

            http.csrf().disable();

Customfailurehandler

public class CustomfailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        request.setAttribute("error","Login inválido");

    }
}

0

If it is just an invalid login message, to display error messages when login fails, I do not set anything in the class, just leave the default, which redirects to the login url? error, then in the view I do the following:

#if($!request.getParameter('error'))
  <div class="alert alert-danger" role="alert">             
    <span>Usuário ou senha inválidos</span>                         
  </div>                        
#end

In this example I used Velocity, with jsp gets:

<c:if test="${param.error != null}">
  <div class="alert alert-danger" role="alert">             
    <span>Usuário ou senha inválidos</span>                         
  </div>    
</c:if>
  • That’s not exactly what I asked, I’d like to treat the condition of authentication failure. for example, invalid login, server off, already logged in user etc. need spring security response to be more sure than to show the user

  • 1

    in the view you have the attribute $SPRING_SECURITY_LAST_EXCEPTION.message with the message of the last exception, I managed to use it for invalid user and disabled user, must have other options and configuring the failureHandler in Securityconfiguration, I think da para criar suas exceptions

  • Yes, but the application runs all over Brazil, thousands of users simultaneously logging in and changing things in the application. this approach is not very clean

Browser other questions tagged

You are not signed in. Login or sign up in order to post.