導讀:上篇文章我們已經抽取出了單獨的認證服務,本章主要內容是讓SpringCloud Gateway 集成Oauth2。
概念部分
在網關集成Oauth2.0后,我們的流程架構如上。主要邏輯如下:
1、客戶端應用通過api網關請求認證服務器獲取access_token http://localhost:8090/auth-service/oauth/token
2、認證服務器返回access_token
{
"access_token": "f938d0c1-9633-460d-acdd-f0693a6b5f4c",
"token_type": "bearer",
"refresh_token": "4baea735-3c0d-4dfd-b826-91c6772a0962",
"expires_in": 43199,
"scope": "web"
}
3、客戶端攜帶access_token通過API網關訪問后端服務
4、API網關收到access_token后通過 AuthenticationWebFilter
對access_token認證
5、API網關轉發后端請求,后端服務請求Oauth2認證服務器獲取當前用戶
在前面文章中我們搭建好了單獨的Oauth2認證授權服務,基本功能框架都實現了,這次主要是來實現第四條,SpringCloud 整合 Oauth2 后如何進行access_token過濾校驗。
代碼示例
引入組件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
主要引入跟oauth2相關的jar包,這里還需要引入數據庫相關的jar包,因為我們的token是存在數據庫中,要想在網關層校驗token的有效性必須先從數據庫取出token。
bootstrap.yml 配置修改
spring:
application:
name: cloud-gateway
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://xx.0.xx.xx:3306/oauth2_config?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: xxxxx
password: xxxxxxx
driver-class-name: com.mysql.jdbc.Driver
主要配置oauth2的數據庫連接地址
自定義認證接口管理類
在webFlux環境下通過實現 ReactiveAuthenticationManager
接口 自定義認證接口管理,由於我們的token是存在jdbc中所以命名上就叫ReactiveJdbcAuthenticationManager
@Slf4j
public class ReactiveJdbcAuthenticationManager implements ReactiveAuthenticationManager {
private TokenStore tokenStore;
public JdbcAuthenticationManager(TokenStore tokenStore){
this.tokenStore = tokenStore;
}
@Override
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.justOrEmpty(authentication)
.filter(a -> a instanceof BearerTokenAuthenticationToken)
.cast(BearerTokenAuthenticationToken.class)
.map(BearerTokenAuthenticationToken::getToken)
.flatMap((accessToken ->{
log.info("accessToken is :{}",accessToken);
OAuth2AccessToken oAuth2AccessToken = this.tokenStore.readAccessToken(accessToken);
//根據access_token從數據庫獲取不到OAuth2AccessToken
if(oAuth2AccessToken == null){
return Mono.error(new InvalidTokenException("invalid access token,please check"));
}else if(oAuth2AccessToken.isExpired()){
return Mono.error(new InvalidTokenException("access token has expired,please reacquire token"));
}
OAuth2Authentication oAuth2Authentication =this.tokenStore.readAuthentication(accessToken);
if(oAuth2Authentication == null){
return Mono.error(new InvalidTokenException("Access Token 無效!"));
}else {
return Mono.just(oAuth2Authentication);
}
})).cast(Authentication.class);
}
}
網關層的安全配置
@Configuration
public class SecurityConfig {
private static final String MAX_AGE = "18000L";
@Autowired
private DataSource dataSource;
@Autowired
private AccessManager accessManager;
/** * 跨域配置 */
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
HttpHeaders requestHeaders = request.getHeaders();
ServerHttpResponse response = ctx.getResponse();
HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
HttpHeaders headers = response.getHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
if (requestMethod != null) {
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
}
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
@Bean
SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception{
//token管理器
ReactiveAuthenticationManager tokenAuthenticationManager = new ReactiveJdbcAuthenticationManager(new JdbcTokenStore(dataSource));
//認證過濾器
AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(tokenAuthenticationManager);
authenticationWebFilter.setServerAuthenticationConverter(new ServerBearerTokenAuthenticationConverter());
http
.httpBasic().disable()
.csrf().disable()
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.anyExchange().access(accessManager)
.and()
// 跨域過濾器
.addFilterAt(corsFilter(), SecurityWebFiltersOrder.CORS)
//oauth2認證過濾器
.addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION);
return http.build();
}
}
這個類是SpringCloug Gateway 與 Oauth2整合的關鍵,通過構建認證過濾器 AuthenticationWebFilter
完成Oauth2.0的token校驗。
AuthenticationWebFilter
通過我們自定義的 ReactiveJdbcAuthenticationManager
完成token校驗。
我們在這里還加入了CORS
過濾器,以及權限管理器 AccessManager
權限管理器
@Slf4j
@Component
public class AccessManager implements ReactiveAuthorizationManager<AuthorizationContext> {
private Set<String> permitAll = new ConcurrentHashSet<>();
private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
public AccessManager (){
permitAll.add("/");
permitAll.add("/error");
permitAll.add("/favicon.ico");
permitAll.add("/**/v2/api-docs/**");
permitAll.add("/**/swagger-resources/**");
permitAll.add("/webjars/**");
permitAll.add("/doc.html");
permitAll.add("/swagger-ui.html");
permitAll.add("/**/oauth/**");
permitAll.add("/**/current/get");
}
/** * 實現權限驗證判斷 */
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) {
ServerWebExchange exchange = authorizationContext.getExchange();
//請求資源
String requestPath = exchange.getRequest().getURI().getPath();
// 是否直接放行
if (permitAll(requestPath)) {
return Mono.just(new AuthorizationDecision(true));
}
return authenticationMono.map(auth -> {
return new AuthorizationDecision(checkAuthorities(exchange, auth, requestPath));
}).defaultIfEmpty(new AuthorizationDecision(false));
}
/** * 校驗是否屬於靜態資源 * @param requestPath 請求路徑 * @return */
private boolean permitAll(String requestPath) {
return permitAll.stream()
.filter(r -> antPathMatcher.match(r, requestPath)).findFirst().isPresent();
}
//權限校驗
private boolean checkAuthorities(ServerWebExchange exchange, Authentication auth, String requestPath) {
if(auth instanceof OAuth2Authentication){
OAuth2Authentication athentication = (OAuth2Authentication) auth;
String clientId = athentication.getOAuth2Request().getClientId();
log.info("clientId is {}",clientId);
}
Object principal = auth.getPrincipal();
log.info("用戶信息:{}",principal.toString());
return true;
}
}
主要是過濾掉靜態資源,將來一些接口權限校驗也可以放在這里。
測試
-
通過網關調用auth-service獲取 access_token
-
在Header上添加認證訪問后端服務
-
網關過濾器進行token校驗
-
權限管理器校驗
-
去認證服務器校驗當前用戶
-
返回正常結果
-
故意寫錯access_token,返回錯誤響應
-
請求頭上去掉access_token,直接返回
401 Unauthorized
總結
通過以上幾步我們將SpringCloud Gateway整合好了Oauth2.0,這樣我們整個項目也基本完成了,后面幾期再來對項目進行優化,歡迎持續關注。
SpringCloud Alibaba 系列文章
- SpringCloud Alibaba微服務實戰系列