上一篇寫了認(rèn)證端(http://www.reibang.com/p/5a76d246b37f)催植,因?yàn)槠^長(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聪黎,這里處理沒有驗(yàn)證身份通過時(shí)進(jìn)入的可都,主要就是沒帶token訪問耕姊,或錯(cuò)誤token的認(rèn)證問題,customAccessDeniedHandler主要就是權(quán)限問題蔚出,不過如果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)沒預(yù)想到的異常來進(jìn)行兜底,如果出現(xiàn)AccessDeniedException趋翻,還是會(huì)走到全局異常處理兜底的那個(gè)異常處理器睛琳,不會(huì)進(jìn)入customAccessDeniedHandler,所以我們最后還是在全局異常處理器中定義個(gè)AccessDeniedException的處理踏烙。
參考文章:https://blog.csdn.net/qq_31063463/article/details/83819944