SoFunction
Updated on 2025-04-14

SpringSecurity throws exception but AccessDeniedHandler does not take effect

Reappearance

@Bean
    public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception {
    	//...
		//abnormal        (except -> {
            (new SecurityAuthenticationEntryPoint());
            ((request, response, e) -> { //Request an unauthorized interface
                //Create the result object                HashMap result = new HashMap();
                ("code", -1);
                ("message", "permission denied");

                //Convert to json string                String json = (result);

                //Return response                ("application/json;charset=UTF-8");
                ().println(json);
            });
            //...
        });

Or throw an exception

: Access Denied
    at (:256) ~[spring-security-core-6.2.:6.2.1]
    at

reason

@RestControllerAdviceGlobal exception intercepted and returned directly, commented out
Or adopt

import 
//...
@ExceptionHandler()
public void accessDeniedException(AccessDeniedException e) throws AccessDeniedException {
	throw e;
}
//...

This is the article about the solution of SpringSecurity throwing exception but AccessDeniedHandler does not take effect. For more related content related to SpringSecurity AccessDeniedHandler, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!