Spring Boot: accessDeniedHandler does not work

前端 未结 4 947
北荒
北荒 2020-12-14 20:44

I\'ve got the following Spring Security configuration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter          


        
4条回答
  •  借酒劲吻你
    2020-12-14 20:50

    Come across this question, it helped me solve my problem, below is my code:

    public class CustomHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
            response.getWriter().print("You need to login first in order to perform this action.");
        }
    
    }
    

    public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException arg2)
                throws IOException, ServletException {
            response.getWriter().print("You don't have required role to perform this action.");
        }
    
    }
    

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()).and()
            .exceptionHandling().authenticationEntryPoint(new CustomHttp403ForbiddenEntryPoint());
    }
    

    Hope this helps.

提交回复
热议问题