REVIEW:我々は独立した認証サービスを抽出してきた前回の記事では、この章の主な内容は、SpringCloudゲートウェイ統合の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に示すように、クライアントは、API Gateway経由でアクセスバックエンドサービスにaccess_tokenは運びます
4、APIゲートウェイを介してaccess_tokenはを受信した後にAuthenticationWebFilter
認証にaccess_tokenは
5、APIゲートウェイは転送し、バックエンドへの要求は、バックエンドのサービス要求のOAuth2認証サーバは、現在のユーザーを取得するには
前回の記事で、我々は良いに別々のOAuth2認証および承認サービスを、基本的な機能のフレームワークが実現されているの構築、これは記事IVを実装するために主に、どのように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パッケージを導入する必要性があります。
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
、当社のトークンがそう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のOAuth2ゲートウェイと統合されAuthenticationWebFilter
たトークンの検証Oauth2.0の完了を。AuthenticationWebFilter
私たちのカスタムを通じてReactiveJdbcAuthenticationManager
トークンの検証を完了します。ここでは、また、追加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;
}
}
复制代码
メインは、将来の権限は、いくつかのインターフェイスを確認し、静的なリソースをフィルタリングすることでもここに配置することができます。
テスト
-
access_tokenは取得のauth-サービスゲートウェイを呼び出すことにより、
-
ヘッダーにアクセスバックエンドサービスへの認証を追加
-
ゲートウェイは、トークンの検証をフィルタリング
-
Rights Managerをチェック
-
現在のユーザーを確認するための認証サーバ
-
正常な結果に戻ります
-
故意に間違ったaccess_tokenは、エラー応答を返します
-
ヘッドaccess_tokenはを削除する要求、ダイレクトリターン
401 Unauthorized
概要
私たちのプロジェクト全体が大幅に完了しているので、我々はSpringCloudゲートウェイプロジェクトの最適化のいくつかを戻ってきて、よくOauth2.0を統合する以上の工程により、持続的注意を歓迎しました。
SpringCloudアリババシリーズ