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); } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM