序文
で春の雲高度道路| 7:ゲートウェイ(zuul)サービングの記事を、だけでなく、往路と要求のフィルタリング、あなたも権限、監査、インターフェースを確認することができゲートウェイの役割と重要性、上で詳述しています監視、電流制限、等のログ収集・ロジック。
これらの追加のロジックを実現するためには、他のフレーム、または適切なフィルタの開発だけでなく、コードまたはロジックを統合するために必要。本論文では、統合セキュリティフレームワークに焦点を当てて、例えば、ゲートウェイを認証する方法を示します。
マイクロサービスアーキテクチャは、マイクロサポートサービスのいくつか、あるいは十に分割大きな単一のアプリケーションおよびサービスに、上述したように、高可用性を確保するために、各マイクロサービスは、クラスタを展開する可能性があります。
前の記事によると、正規サービス(春クラウドのOAuth2):8 |春の雲高度道路、春の雲高度道路| 9:リソースサービス(春クラウドのOAuth2)博覧会の後に単一のサービス、サーバーリソースが分割され、リソースのサービスを提供しています。
それがサービスを提供するために、外部のリソースであるので、問題、すなわち、セキュリティ上の問題を引き起こすことがバインドされています。このとき、二つの選択肢があるでしょう:各リソースサービスの裁量、ゲートウェイ・プロセスによって統一され、各リソースサービスは、唯一のビジネスに焦点を当てます。
各リソースサービスが扱う場合は、マイクロサービス分割後、各サービスロジックは、同じセキュリティを処理するために必要な深刻な繰り返しワークロード。でも公開部分を抽出し、大きな問題を解決することはできません。公開部分のみが認証の問題を解決しているので、各リソースの権限が異なっているため、認証サービスを解決しません。
ゲートウェイハンドルで統一し、リソースサービス、初期直接認証、後の認証によって認証などゲートウェイ自体は、採択した後、次の論理的に進んでいます。この場合、各リソースのサービスは、面倒なセキュリティポリシーに対処することなく、自分のビジネスを懸念。
権利の問題については、権利は、ユーザー権限のすべてのリソースとサービスの統合管理を統一支持プラットフォームを開発するために、リソースラインが自動的に保守要員への均一な分布によって、その後のサポートの許可にサービスプラットフォームに登録されており、。
準備
前リユース記事へのゲートウェイ(Zuul)のサービング:七|春の雲高度道路、春の雲高度道路|八:正規サービス(春雲のOAuth2) 、春の雲高度道路| 9:リソースサービス(春クラウドOAuth2)プロジェクト。
変換xmall製品
以前によれば、各リソースサービスは存在しません認定サービスリソースサービスの相対として春の雲のOAuth2関連するコンテンツを削除するため、必要があります。
削除春の雲のOAuth2依存
次のようにポンポンファイルが変更されました。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.luas.cloud</groupId>
<artifactId>java-boot-parent-2.1</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../java-boot-parent-2.1</relativePath>
</parent>
<groupId>com.luas.cloud</groupId>
<artifactId>xmall-product</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>xmall-product</name>
<description>Spring Cloud Learning,nacos-client</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- nacos cloud -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
削除のOAuth2のリソース
OAuth2リソースの構成情報の削除application.yml、次のように削除します。
server:
port: 8080
削除ResourceServer構成
クラスを開始することがあるような@EnableResourceServerノートを、それが削除されます。
package com.luas.xmall;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class XmallProductApplication {
public static void main(String[] args) {
SpringApplication.run(XmallProductApplication.class, args);
}
}
ResourceServerConfigurationの設定クラスが存在しているとして、それが削除されます。
package com.luas.xmall.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.anyRequest()
.and()
.authorizeRequests()
.antMatchers("/application").permitAll()
.anyRequest()
.authenticated();
}
}
復興ゲートウェイ
春の雲のOAuth2は従属追加します
次のように春 - クラウド・スタータのOAuth2依存、POM変更されたファイルを追加します。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.luas.cloud</groupId>
<artifactId>java-boot-parent-2.1</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../java-boot-parent-2.1</relativePath>
</parent>
<groupId>com.luas.xmall</groupId>
<artifactId>xmall-zuul</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>xmall-zuul</name>
<description>网关服务</description>
<properties>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<!-- nacos cloud -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
アプリケーション構成を変更します
追加の認証サーバーのルーティングルール、資源の配分のOAuth2を。
server:
port: 5566
zuul:
prefix: /gateway
sensitive-headers:
routes:
auth:
path: /auth/**
service-id: xmall-auth
strip-prefix: true
product:
path: /product/**
service-id: xmall-product
strip-prefix: true
security:
oauth2:
resource:
user-info-uri: http://localhost:7777/oauth/user
prefer-token-info: false
ResourceServerConfigurationの設定クラスを追加します。
なぜあなたは直接@EnableResourceServerスタートアップクラスのオープンリソースサービス注釈を追加していない、との特別なリソースサービスの構成を定義する:ここでのポイント、より重要なのはありますか?
その理由は、デフォルトのリソースサーバーのセキュリティポリシー、要求に必要な認証は、アクセスにこれらおよび他のIDの認証を取得する必要がなく、トークン、トークン検証、トークンキーのエンドポイントを取得することで、ブロックされます。したがって、特別の定義は、リソースサービスのセキュリティポリシー、これらのエンドポイントの一般公開が必要です。
次のようにResourceServerConfigurationクラスがあります。
package com.luas.xmall.gateway.configuration;
import com.luas.xmall.gateway.filter.PreAuthenticationFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.anyRequest()
.and()
.authorizeRequests()
.antMatchers("/application").permitAll()
// 放开token授权、token key获取、token验证端点
.antMatchers(PreAuthenticationFilter.TOKEN_ENDPOINT).permitAll()
.antMatchers(PreAuthenticationFilter.TOKEN_KEY_ENDPOINT).permitAll()
.antMatchers(PreAuthenticationFilter.CHECK_TOKEN_ENDPOINT).permitAll()
.anyRequest()
.authenticated();
}
}
変換PreAuthenticationFilter
ResourceServerConfigurationでは、事前セキュリティチェックもオープン公共のエンドポイントである必要があり。さらに、このフィルタは、ユーザ情報解析及び送信ロジックのように、関連する権利を傍受してもよいです。その他としては、このような監査インターフェースとして、フィルタは、しかし、別のプロセスを作成することができる実行し、フィルタタイプの順序に注意してください。
package com.luas.xmall.gateway.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
@Component
public class PreAuthenticationFilter extends ZuulFilter {
public static final String TOKEN_ENDPOINT = "/gateway/auth/oauth/token";
public static final String TOKEN_KEY_ENDPOINT = "/gateway/auth/oauth/token_key";
public static final String CHECK_TOKEN_ENDPOINT = "/gateway/auth/oauth/check_token";
private Logger logger = LoggerFactory.getLogger(getClass());
private TokenExtractor tokenExtractor = new BearerTokenExtractor();
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
String requestURI = request.getRequestURI();
return !(requestURI.equals(TOKEN_ENDPOINT) && requestURI.equals(TOKEN_KEY_ENDPOINT) && requestURI.equals(CHECK_TOKEN_ENDPOINT));
}
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
if (this.logger.isDebugEnabled()) {
this.logger.debug("uri {}", request.getRequestURI());
}
Authentication authentication = this.tokenExtractor.extract(request);
if (authentication == null || authentication.getPrincipal() == null) {
//不会继续往下执行 不会调用服务接口了 网关直接响应给客户了
requestContext.setSendZuulResponse(false);
requestContext.setResponseBody("Full authentication is required to access this resource");
requestContext.setResponseStatusCode(401);
return null;
}
String accessToken = (String) authentication.getPrincipal();
this.logger.info("token {}", accessToken);
// todo 解析token,调用权限支撑平台,获取权限信息,组织到用户信息中传递给下游微服务
return null;
}
}
検証
ターンで開始し、xmall製品、xmall-zuul、それぞれ7777,8080,5566ポート-AUTHをxmall。
最初の直接アクセスは、http:// localhostを:8080 / SKU / 1122、通常の訪問することができます。
// localhostを::HTTPゲートウェイに移動5566 /ゲートウェイ/製品/ SKU / 1122は、あなたが認証される必要がある、通常の訪問を見つけることができませんでした。
認可を呼び出すことによって、ゲートウェイサービス、認証、アドレス:
http:// localhostを:?5566 /ゲートウェイ/認証/ OAuthの/トークンのclient_id = client_1&client_secret = 123456&ユーザ名= USER_1&パスワード= 123456&スコープ=サーバー&grant_type =パスワード。
通常の返品承認結果を要求した後。
この時点では、成功した変換ゲートウェイを示し、適切に認証のために要求されたリソースフェデレーションサーバー用に認可サーバリソースの役割を果たしてきました。
キャリー承認、再訪問のhttpのヘッダ道:// localhostを:/ SKU / 1122 8080は、通常の訪問することができます。
网关整合安全框架以在网关进行身份认证完成,其它功能如日志收集、接口审计、鉴权等,读者可自行去参整合实现。后续也会出相关文章,对部分功能进行整合说明。
源码
github
https://github.com/liuminglei/SpringCloudLearning/tree/master/10/
gitee
https://gitee.com/xbd521/SpringCloudLearning/tree/master/10/
微信搜索【银河架构师】,发现更多精彩内容。