spring security 以及 oauth2

spring security oauth2 资源端异常处理(

2021-10-13  本文已影响0人  virtual灬zzZ

上一篇写了认证端(https://www.jianshu.com/p/5a76d246b37f),因为篇幅过长,所以资源端另外写。

资源端

资源端相对简单一些:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true)
public class Oauth2JdbcResourceConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "hahaRsId";

    @Autowired
    private DataSource dataSource;

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    private AuthenticationManager authenticationManager;

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

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/myoauth/**").authenticated();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
                .tokenStore(jdbcTokenStore())
                .stateless(true)
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .accessDeniedHandler(customAccessDeniedHandler);
                //.authenticationManager(authenticationManager);
    }

    @Bean
    public TokenStore jdbcTokenStore(){
        return new JdbcTokenStore(dataSource);
    }

}

这里注意的是,自定义一个customAuthenticationEntryPoint,这里处理没有验证身份通过时进入的,主要就是没带token访问,或错误token的认证问题,customAccessDeniedHandler主要就是权限问题,不过如果controller有异常的话,不会走到这两个类中的,所以我们一般都会搞一下全局异常类,类似下面的。

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DateTimeParseException.class)
    public Result actionDtpeExceptionHandle(DateTimeParseException dtpe
            , HttpServletRequest request) {
        log.warn("发生DateTimeParseException异常({}) :", request.getRequestURI(), dtpe);
        return CommonCodeEnum.COMMON_INVALID_PARAM.toResult();
    }
}

@ExceptionHandler(Exception.class)
    public Result methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException methodArgumentNotValidException
            , HttpServletRequest request) {
        log.warn("发生MethodArgumentNotValidException异常({}) :", request.getRequestURI(), methodArgumentNotValidException);
        return CommonCodeEnum.COMMON_INVALID_PARAM.toResult();
    }

我们一般都在结尾布置上一个总的exceptionHandler,防止出现没预想到的异常来进行兜底,如果出现AccessDeniedException,还是会走到全局异常处理兜底的那个异常处理器,不会进入customAccessDeniedHandler,所以我们最后还是在全局异常处理器中定义个AccessDeniedException的处理。

参考文章:https://blog.csdn.net/qq_31063463/article/details/83819944

上一篇下一篇

猜你喜欢

热点阅读