上一篇寫了認(rèn)證端(http://www.itdecent.cn/p/5a76d246b37f),因?yàn)槠^(guò)長(zhǎng),所以資源端另外寫。
資源端
資源端相對(duì)簡(jiǎn)單一些:
@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);
}
}
這里注意的是,自定義一個(gè)customAuthenticationEntryPoint,這里處理沒(méi)有驗(yàn)證身份通過(guò)時(shí)進(jìn)入的,主要就是沒(méi)帶token訪問(wèn),或錯(cuò)誤token的認(rèn)證問(wèn)題,customAccessDeniedHandler主要就是權(quán)限問(wèn)題,不過(guò)如果controller有異常的話,不會(huì)走到這兩個(gè)類中的,所以我們一般都會(huì)搞一下全局異常類,類似下面的。
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DateTimeParseException.class)
public Result actionDtpeExceptionHandle(DateTimeParseException dtpe
, HttpServletRequest request) {
log.warn("發(fā)生DateTimeParseException異常({}) :", request.getRequestURI(), dtpe);
return CommonCodeEnum.COMMON_INVALID_PARAM.toResult();
}
}
@ExceptionHandler(Exception.class)
public Result methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException methodArgumentNotValidException
, HttpServletRequest request) {
log.warn("發(fā)生MethodArgumentNotValidException異常({}) :", request.getRequestURI(), methodArgumentNotValidException);
return CommonCodeEnum.COMMON_INVALID_PARAM.toResult();
}
我們一般都在結(jié)尾布置上一個(gè)總的exceptionHandler,防止出現(xiàn)沒(méi)預(yù)想到的異常來(lái)進(jìn)行兜底,如果出現(xiàn)AccessDeniedException,還是會(huì)走到全局異常處理兜底的那個(gè)異常處理器,不會(huì)進(jìn)入customAccessDeniedHandler,所以我們最后還是在全局異常處理器中定義個(gè)AccessDeniedException的處理。
參考文章:https://blog.csdn.net/qq_31063463/article/details/83819944