SpringBoot捕获AccessDeniedExceptio

作者: 褪色的记忆1994 | 来源:发表于2018-10-24 13:12 被阅读21次
    自定义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

    微信公众号

    微信公众号

    相关文章

      网友评论

        本文标题:SpringBoot捕获AccessDeniedExceptio

        本文链接:https://www.haomeiwen.com/subject/aakgzftx.html