詳解spring cloud ouath2中的資源服務器
資源服務器就是業(yè)務服務 如用戶服務,訂單服務等 第三方需要到資源服務器調(diào)用接口獲取資源
ResourceServerConfig
ResourceServerConfig是資源服務器的核心配置 用于驗證token 與網(wǎng)關配置相似
其中.antMatchers("/**").access("#oauth2.hasScope('user')") 需要oauth_client_details表的scope配合 意思是訪問所有資源 需要客戶端有scope需要有user

@Configuration
@EnableResourceServer // 標識為資源服務器,請求服務中的資源,就要帶著token過來,找不到token或token是無效訪問不了資源
@EnableGlobalMethodSecurity(prePostEnabled = true) // 開啟方法級別權限控制
public class ResourceServerConfig extends ResourceServerConfigurerAdapter implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);
public static final String RESOURCE_ID = "user";
/**
* 權限不足返回給前端json
*/
@Autowired
private CustomAccessDeniedHandlerConfig customAccessDeniedHandlerConfig;
@Autowired
private TokenStore tokenStore;
/**
* token無效返回前段json
*/
@Autowired
private AuthExceptionEntryPointConfig authExceptionEntryPointConfig;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// 當前資源服務器的資源id,認證服務會認證客戶端有沒有訪問這個資源id的權限,有則可以訪問當前服務
resources.tokenStore(tokenStore).resourceId(RESOURCE_ID)
// token無效異常的處理
.authenticationEntryPoint(authExceptionEntryPointConfig)
// 權限不足異常處理類
.accessDeniedHandler(customAccessDeniedHandlerConfig)
// 會話機制stateless開啟
.stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
// SpringSecurity不會使用也不會創(chuàng)建HttpSession實例 因為整個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
@Component
public 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, "權限不足");
response.getWriter().write(new ObjectMapper().writeValueAsString(result));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Component
public 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, "認證失敗,無效或過期token");
response.getWriter().write(new ObjectMapper().writeValueAsString(result));
} else {
result = new Result(401, "認證失敗,沒有攜帶token");
response.sendRedirect(redirectUrl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
TokenConfig
不多說
@Configuration
public class TokenConfig{
/**
* 使用redis存儲
*/
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
}
application.yml
那么小伙伴又問了 既然網(wǎng)關驗證token的有效性 那么資源服務器是不是就不用驗證啦 答案是否 因為不添加配置 會報錯 同樣需要在application中添加以下配置
其他配置也spirng boot為準 這里不多說
security: oauth2: client: client-id: user-vue client-secret: 1234 resource: token-info-uri: http://localhost:8001/oauth/check_token
到此這篇關于spring cloud ouath2中的資源服務器的文章就介紹到這了,更多相關spring cloud ouath2資源服務器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MyBatis入門實例教程之創(chuàng)建一個簡單的程序
這篇文章主要介紹了MyBatis入門創(chuàng)建一個簡單的程序,在?MySQL?中創(chuàng)建數(shù)據(jù)庫?mybatisdemo,編碼為?utf8,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-02-02
SpringCloud-Gateway網(wǎng)關的使用實例教程
Gateway網(wǎng)關在微服務架構中扮演了不可或缺的角色,通過集中化管理、智能路由和強大的過濾器機制,為構建高效、可擴展的微服務系統(tǒng)提供了有力支持,這篇文章主要介紹了SpringCloud-Gateway網(wǎng)關的使用,需要的朋友可以參考下2024-03-03
springboot 啟動項目打印接口列表的實現(xiàn)
這篇文章主要介紹了springboot 啟動項目打印接口列表的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
SpringBoot項目啟動過程動態(tài)修改接口請求路徑的解決方案
在SpringBoot服務整合過程中,遇到了多個服務中相同RequestMapping路徑導致的啟動問題,解決方案是通過修改RequestMappingHandlerMapping類的getMappingForMethod方法,本文給大家介紹SpringBoot修改接口請求路徑的解決方案,感興趣的朋友一起看看吧2024-09-09

