方法1

1、自定义RewriteAccessDenyFilter类,内容为:

/**
 * @ClassName: RewriteAccessDenyFilter
 * @Description: 捕捉异常
 * @Author ye21st ye21st@gmail.com
 * @Date 2020/7/7 10:35 上午:45
 */
public class RewriteAccessDenyFilter extends GenericFilterBean {

    @Autowired
    private MessageService messageServiceImpl;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        if(messageServiceImpl == null){
            ServletContext servletContext = request.getServletContext();
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            assert webApplicationContext != null;
            messageServiceImpl = webApplicationContext.getBean(MessageServiceImpl.class);
        }
        try {
            filterChain.doFilter(request, response);
        } catch (AccessDeniedException e) {
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            String msg = messageServiceImpl.getMessage(CommonMessage.NO_ACCESS);
            response.getWriter().write(JacksonUtil.obj2json(new ResultDto(BizExceptionEnum.NO_ACCESS, msg)));
        }
    }
}

2、将过滤器引入到SpringSecurity配置当中:

/**
 * @ClassName: SpringSecurityConfig
 * @Description:
 * @Author ye21st
 * @Date 2020年07月08日12:27:47
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AdminRestProperties properties;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] noAuthPath = properties.getNotAuthPath().toArray(new String[properties.getNotAuthPath().size()]);

        http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(noAuthPath).permitAll()
                .antMatchers("/druid/**").anonymous()
                .anyRequest().authenticated()
                .and()
                .addFilterAfter(new RewriteAccessDenyFilter(), ExceptionTranslationFilter.class)
                .addFilterBefore(new RewriteAccessDenyFilter(), FilterSecurityInterceptor.class)
                .headers().cacheControl();
    }
}

方法2

1、自定义EntryPointUnauthorizedHandler类:

/**
 * @ClassName: EntryPointUnauthorizedHandler
 * @Description:
 * @Author ye21st ye21st@gmail.com
 * @Date 2020/7/8 10:58 上午:26
 */
@Component
public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint {

    @Autowired
    private MessageService messageServiceImpl;

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        String msg = messageServiceImpl.getMessage(CommonMessage.NO_ACCESS);
        httpServletResponse.getWriter().write(JacksonUtil.obj2json(new ResultDto(BizExceptionEnum.NO_ACCESS, msg)));
    }
}

2、自定义RestAccessDeniedHandler类:

/**
 * @ClassName: RestAccessDeniedHandler
 * @Description:
 * @Author ye21st ye21st@gmail.com
 * @Date 2020/7/7 2:27 下午:06
 */
@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private MessageService messageServiceImpl;

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        String msg = messageServiceImpl.getMessage(CommonMessage.NO_ACCESS);
        httpServletResponse.getWriter().write(JacksonUtil.obj2json(new ResultDto(BizExceptionEnum.NO_ACCESS, msg)));
    }
}

3、将EntryPointUnauthorizedHandler以及RestAccessDeniedHandlerSpringSecurity中进行配置:

/**
 * @ClassName: SpringSecurityConfig
 * @Description:
 * @Author ye21st
 * @Date 2020年07月08日12:27:47
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AdminRestProperties properties;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] noAuthPath = properties.getNotAuthPath().toArray(new String[properties.getNotAuthPath().size()]);

        http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(noAuthPath).permitAll()
                .antMatchers("/druid/**").anonymous()
                .anyRequest().authenticated()
                .and()
                .headers().cacheControl();

http.exceptionHandling().authenticationEntryPoint(entryPointUnauthorizedHandler).accessDeniedHandler(restAccessDeniedHandler);
    
    }
}
Last modification:December 18, 2020
If you think my article is useful to you, please feel free to appreciate