SpringBoot捕获AccessDeniedException

自定义AccessDeniedHandler
/**
 * @Author: jialing xu
 * @Description: xvjialing@outlook.com
 * @Date: 17:24 2018/8/7
 */
@Service
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        Map map = new HashMap();
        map.put("code", "403");
        map.put("msg", accessDeniedException.getMessage());
        map.put("data","");
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(objectMapper.writeValueAsString(map));
    }
}
将CustomAccessDeniedHandler加到configure中

    @Autowired
    CustomAccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .antMatchers("/actuator","/actuator/**").permitAll()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    }

}

个人博客:https://blog.xvjialing.xyz

github主页:https://github.com/xvjialing

微信公众号

微信公众号
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。