解决spring cloud 中使用spring security全局异常处理器失效

写auth认证模块实现忘记密码与注册功能时,用异常抛出,全局异常处理器无法捕获。
解决spring cloud 中使用spring security全局异常处理器失效_第1张图片
无法进行异常捕捉

解决spring cloud 中使用spring security全局异常处理器失效_第2张图片
解决spring cloud 中使用spring security全局异常处理器失效_第3张图片
解决方案:使用WebSecurityConfigurerAdapter.configure中http实现自定义异常:

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 //配置安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
                .authorizeRequests()
                .antMatchers("/r/**").authenticated()//访问/r开始的请求需要认证通过
                .anyRequest().permitAll()//其它请求全部放行
                .and()
                .exceptionHandling()
                // 认证异常处理handler 使用的 lambda的内部的实现
                .authenticationEntryPoint((request, response, authenticationException) -> {
                    RestErrorResponse restErrorResponse = new RestErrorResponse(authenticationException.getMessage());//自定义返回类
                    response.setStatus(401);
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.getWriter().println(JSON.toJSONString(restErrorResponse));

                })
                // 授权异常处理handler 使用的 lambda的内部的实现
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    RestErrorResponse restErrorResponse = new RestErrorResponse(accessDeniedException.getMessage());//自定义返回类
                    response.setStatus(401);
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.getWriter().println(JSON.toJSONString(restErrorResponse));
                })
                .and()
                .formLogin().successForwardUrl("/login-success");//登录成功跳转到/login-success
    }


代码抛出异常要是security中的异常类,不然还是捕获不到
解决spring cloud 中使用spring security全局异常处理器失效_第4张图片

解决spring cloud 中使用spring security全局异常处理器失效_第5张图片

你可能感兴趣的:(java,#,spring,#,springboot,spring,spring,cloud,后端,微服务,springcloud,分布式,java)