Why Spring Security is not working accessDaniedHandler?

Hello, this situation, I want to configure spring security men so that when someone climbed a non-existent page or the pages were redirected to a page - access denied. But the fact is that when I try to do a query on a left path, it redirects me to the login page as if I authentication entered incorrect data! I added to the settings page in the case of "access denied" also added khadler, but the logs do not rabotat, that is, it doesn't work... Why?
Maybe I misunderstand how it should work?! I understand it so that when you enter the left or the forbidden paths, that is, where the user has no rights, I should throw the error page, but somehow throws in the login page...
little update:
accessDeniedHandler only works if I Selaginella and try to log in to an existing restricted page. Why it does not work if I razlozhenny and try to log in to an existing restricted page and going straight to the login page?

Configure Spring Security Men
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
 myAuthenticationSuccessHandler public AuthenticationSuccessHandler() {
 return new MyAuthenticationSuccessHandler();
}

@Bean
 public UserDetailsServiceImpl userDetailsService() {
 return new UserDetailsServiceImpl();
}

@Bean
 public AccessDeniedHandler accessDeniedHandler() {
 return new MyAccessDeniedHandler();
}

@Bean
 public BCryptPasswordEncoder bCryptPasswordEncoder() {
 return new BCryptPasswordEncoder();
}

@Bean
 public DaoAuthenticationProvider daoAuthenticationProvider () {
 DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
 return authenticationProvider;
}

@Override
 protected void configure(AuthenticationManagerBuilder amb) throws Exception {
amb.authenticationProvider(daoAuthenticationProvider());
}

@Override
 public void configure(WebSecurity web) throws Exception {
// the web.debug(true);
web.ignoring()
.antMatchers("/resources/**")
.antMatchers("/resources/bootstrapComponent/**")
.antMatchers("/resources/css/**")
.antMatchers("/resources/patternViews/**");
}

@Override
 protected void configure(HttpSecurity http) throws Exception {
http.headers()
.defaultsDisabled()
.contentTypeOptions().and()
.frameOptions().and()
.xssProtection()
.block(true).and()
 .contentSecurityPolicy ( "script-src 'self'").and()
.cacheControl();
http.authorizeRequests()
 .antMatchers("/main", "/signin", "/signUp"/*, "/error"*/).permitAll()
 .antMatchers("/home").hasAnyRole("CEO", "Manager", "User")
 .antMatchers("/control").hasAnyRole("CEO", "Manager")
.antMatchers("/ceo").hasAnyRole("CEO")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/signin")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/signin")
// .defaultSuccessUrl("/processSignIn")
// .successForwardUrl("/processSignIn")
.successHandler(myAuthenticationSuccessHandler())
.and()
.logout()
.logoutUrl("/signout")
.logoutSuccessUrl("/signin")
.and()
// .exceptionHandling().accessDeniedPage("/error");
.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}
}

Handler
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
 private final Logger logger = LogManager.getLogger(MyAccessDeniedHandler.class);

@Override
 public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
 logger.debug("DEBUG from MyAccessDeniedHandler -->" + e.getMessage());
 httpServletResponse.sendRedirect( httpServletRequest.getContextPath() + "/error");
}
}

What I need to add or how to solve it!?
Thank you!
April 19th 20 at 12:02
1 answer
April 19th 20 at 12:04
Solution
accessDeniedHandler only works if I Selaginella and try to log in to an existing restricted page. Why it does not work if I razlozhenny and try to log in to an existing restricted page and going straight to the login page?


You have answered your own question. Passing the chain he first runs into the problem of authorization and throws an exception Access Denied Exception.
Ie, first it checks antMatchers and sees that the requested URl is not listed inpermitAll()passing down the chain, he stumbles upon .anyRequest().authenticated() gives Access Denied Exception.

In addition, you have line /error commented out. It is possible that he is trying to show the error, but since this page is not available being unauthorized, at first, going straight to the login page...

Try to raskomentiruyte this line and check if it works.
If not, then try to create a controller:

@Controller
public class HttpErrorController implements ErrorController {

 private final MessageSource messageSource;

@Autowired
 public HttpErrorController(MessageSource messageSource) {
 this.messageSource = messageSource;
}

@RequestMapping("/error")
 public String handleError(
 Locale Locale,
 Model model,
 HttpServletRequest request,
 Exception ex
 ) {

 Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

 if (status != null) {

 int statusCode = Integer.valueOf(status.toString());

 Map<String, String> metaData = new HashMap<>();

 // 403
 if (statusCode == HttpStatus.FORBIDDEN.value()) {

 //do somthing
}

 // 404
 else if (statusCode == HttpStatus.NOT_FOUND.value()) {
 //do somthing
}

 // 405
 else if (statusCode == HttpStatus.NOT_FOUND.value()) {
 //do somthing
}

 // 500
 else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
 //do somthing
}

}


 return "errors/httperrors";
}

@Override
 public String getErrorPath() {
 return "/error";
}

}
Thanks for the reply, but recomendavel the line does not solve my question, and indeed why open access to the user to the error page, I mean that he she can go, and that I think is bad...
Most likely what I want can not be solved only by this approach...
Question closed as this is not a campaign reshaetsya the approach I have chosen to further more errors to handle... - Tiana.Powlowski commented on April 19th 20 at 12:07

Find more questions by tags SpringJava