詳解spring cloud ouath2中的資源服務(wù)器
資源服務(wù)器就是業(yè)務(wù)服務(wù) 如用戶服務(wù),訂單服務(wù)等 第三方需要到資源服務(wù)器調(diào)用接口獲取資源
ResourceServerConfigResourceServerConfig是資源服務(wù)器的核心配置 用于驗(yàn)證token 與網(wǎng)關(guān)配置相似
其中.antMatchers('/**').access('#oauth2.hasScope(’user’)') 需要oauth_client_details表的scope配合 意思是訪問所有資源 需要客戶端有scope需要有user
@Configuration@EnableResourceServer // 標(biāo)識為資源服務(wù)器,請求服務(wù)中的資源,就要帶著token過來,找不到token或token是無效訪問不了資源@EnableGlobalMethodSecurity(prePostEnabled = true) // 開啟方法級別權(quán)限控制public class ResourceServerConfig extends ResourceServerConfigurerAdapter implements CommandLineRunner { private final static Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class); public static final String RESOURCE_ID = 'user'; /** * 權(quán)限不足返回給前端json */ @Autowired private CustomAccessDeniedHandlerConfig customAccessDeniedHandlerConfig; @Autowired private TokenStore tokenStore; /** * token無效返回前段json */ @Autowired private AuthExceptionEntryPointConfig authExceptionEntryPointConfig; @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { // 當(dāng)前資源服務(wù)器的資源id,認(rèn)證服務(wù)會認(rèn)證客戶端有沒有訪問這個(gè)資源id的權(quán)限,有則可以訪問當(dāng)前服務(wù) resources.tokenStore(tokenStore).resourceId(RESOURCE_ID) // token無效異常的處理 .authenticationEntryPoint(authExceptionEntryPointConfig) // 權(quán)限不足異常處理類 .accessDeniedHandler(customAccessDeniedHandlerConfig) // 會話機(jī)制stateless開啟 .stateless(true); } @Override public void configure(HttpSecurity http) throws Exception { http.sessionManagement() // SpringSecurity不會使用也不會創(chuàng)建HttpSession實(shí)例 因?yàn)檎麄€(gè)oauth2后使用token .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() // 開放swagger請求 .antMatchers('/swagger-ui.html', '/webjars/**', '/swagger-resources/**','/v2/**').permitAll() // 所有請求,都需要有all范圍(scope) .antMatchers('/**').access('#oauth2.hasScope(’user’)'). anyRequest().authenticated().and().csrf() .disable(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }}
AuthExceptionEntryPointConfig,CustomAccessDeniedHandlerConfig
用于異常返回前端json
@Componentpublic class CustomAccessDeniedHandlerConfig implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { response.setStatus(HttpStatus.OK.value()); response.setHeader('Content-Type', 'application/json;charset=UTF-8'); try { Result result = new Result(403, '權(quán)限不足'); response.getWriter().write(new ObjectMapper().writeValueAsString(result)); } catch (IOException e) { e.printStackTrace(); } }}
@Componentpublic class AuthExceptionEntryPointConfig implements AuthenticationEntryPoint{ private final static Logger logger = LoggerFactory.getLogger(AuthExceptionEntryPointConfig.class); @Value('${security.redirect-url}') private String redirectUrl; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { Throwable cause = authException.getCause(); response.setStatus(HttpStatus.OK.value()); response.setHeader('Content-Type', 'application/json;charset=UTF-8'); Result result; try { if (cause instanceof InvalidTokenException) { result = new Result(402, '認(rèn)證失敗,無效或過期token'); response.getWriter().write(new ObjectMapper().writeValueAsString(result)); } else { result = new Result(401, '認(rèn)證失敗,沒有攜帶token'); response.sendRedirect(redirectUrl); } } catch (IOException e) { e.printStackTrace(); } }}
TokenConfig
不多說
@Configurationpublic class TokenConfig{ /** * 使用redis存儲 */ @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public TokenStore tokenStore() { return new RedisTokenStore(redisConnectionFactory); } }
application.yml
那么小伙伴又問了 既然網(wǎng)關(guān)驗(yàn)證token的有效性 那么資源服務(wù)器是不是就不用驗(yàn)證啦 答案是否 因?yàn)椴惶砑优渲?會報(bào)錯(cuò) 同樣需要在application中添加以下配置
其他配置也spirng boot為準(zhǔn) 這里不多說
security: oauth2: client: client-id: user-vue client-secret: 1234 resource: token-info-uri: http://localhost:8001/oauth/check_token
到此這篇關(guān)于spring cloud ouath2中的資源服務(wù)器的文章就介紹到這了,更多相關(guān)spring cloud ouath2資源服務(wù)器內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. WML語言的基本情況4. XML入門的常見問題(四)5. 匹配模式 - XSL教程 - 46. ASP中if語句、select 、while循環(huán)的使用方法7. ASP中解決“對象關(guān)閉時(shí),不允許操作?!钡脑幃悊栴}……8. xml中的空格之完全解說9. CSS3中Transition屬性詳解以及示例分享10. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁的問題
