Question:
I'm a little lost here, I would like to put a parameter in the view to inform the user that their 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() )
is never executed!
Answer:
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");
}
}