'My Custom AccessDeniedHandler cannot called

In my Spring Boot app,I have implemented a custom AccessDeniedHandler,but it never called,and the custom authenticationEntryPoint instead of it

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;
    
    @Autowired
    private YzlAccessDeniedHandler yzlAccessDeniedHandler;
    
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/yzl/**").access("@yzlAccessImpl.hasPermit(request)")
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        httpSecurity.exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .accessDeniedHandler(yzlAccessDeniedHandler);
    }
}

the custom AccessDeniedHandler

@Component
public class YzlAccessDeniedHandler implements AccessDeniedHandler, Serializable
{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(403);
response.getWriter().write("Forbidden: access error" + accessDeniedException.getMessage());
}
}

the custom AuthenticationEntryPointImpl

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
        response.setStatus(401);
        response.getWriter().write("Forbidden: Authentication failed");
    }

}

I let the custom Method in the accessImpl return false always,and I expect the response is ""Forbidden: access error" while it was "Forbidden: Authentication failed".

@Component 
public class YzlAccessImpl implements YzlAccess 
{     
 @Override     
 public boolean hasPermit(HttpServletRequest request) {         
 return false;     
 } 
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source