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
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 myAuthenticationSuccessHandler public AuthenticationSuccessHandler() {
 return new MyAuthenticationSuccessHandler();

 public UserDetailsServiceImpl userDetailsService() {
 return new UserDetailsServiceImpl();

 public AccessDeniedHandler accessDeniedHandler() {
 return new MyAccessDeniedHandler();

 public BCryptPasswordEncoder bCryptPasswordEncoder() {
 return new BCryptPasswordEncoder();

 public DaoAuthenticationProvider daoAuthenticationProvider () {
 DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
 return authenticationProvider;

 protected void configure(AuthenticationManagerBuilder amb) throws Exception {

 public void configure(WebSecurity web) throws Exception {
// the web.debug(true);

 protected void configure(HttpSecurity http) throws Exception {
 .contentSecurityPolicy ( "script-src 'self'").and()
 .antMatchers("/main", "/signin", "/signUp"/*, "/error"*/).permitAll()
 .antMatchers("/home").hasAnyRole("CEO", "Manager", "User")
 .antMatchers("/control").hasAnyRole("CEO", "Manager")
// .defaultSuccessUrl("/processSignIn")
// .successForwardUrl("/processSignIn")
// .exceptionHandling().accessDeniedPage("/error");

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

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

public class HttpErrorController implements ErrorController {

 private final MessageSource messageSource;

 public HttpErrorController(MessageSource messageSource) {
 this.messageSource = messageSource;

 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";

 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