Spring Cloud複数のマイクロサービスに統一された認証と承認を実装するためにOAUTH2必要です。中央認証と承認のために特定のタイプのgrant type OAUTH服务に送信することにより、 access_tokenが取得されます。このトークンは、他のマイクロサービスによって信頼されています。後続のアクセスにaccess_tokenを使用して、マイクロサービスの統一された認証と承認を実現できます。
この例は、4つの主要な部分を提供します。
discovery-service :サービス登録と発見のための基本モジュールauth-server :OAUTH2認定および認証センターorder-service :認証と承認を確認するために使用される通常のマイクロサービスapi-gateway :Border Gateway(すべてのマイクロサービスが背後にあります)OAuth2の役割:
Resource Server :アクセスを許可されたリソースAuthotization Server :OAUTH2認定認可センターResource Owner :ユーザーClient :APIを使用しているクライアント(Android、iOS、Webアプリなど)助成金タイプ:
Authorization Code :サーバーアプリケーション間で使用されますImplicit :モバイルアプリまたはWebアプリで使用されます(これらのアプリは、携帯電話でWeChatを規制して認証および承認を行うなど、ユーザーのデバイス上にあります)Resource Owner Password Credentials(password) :アプリケーションは直接信頼されます(すべて会社によって開発され、この例が使用されますClient Credentials :アプリケーションAPIアクセスで使用されます。1。基本環境
アカウントストレージとしてPostgres使用し、 TokenストレージとしてRedis使用し、 docker-composeを使用してサーバーでPostgresとRedis起動します。
Redis:Image:Sameersbn/Redis:最新のポート: - "6379:6379"ボリューム: - /srv/docker/redis:/var/lib/redis:z restart:lestart:restart:warday image:samesbn/postgresql:9.6-2ポート:-5432:5432 "環境: -db_pass = yunfei -db_name =注文ボリューム: - /srv/docker/postgresql:/var/lib/postgresql:z
2.auth-server
2.1 OAUTH2サービス構成
Redis tokenを保存するために使用されます。サービスが再起動した後、 token再獲得する必要はありません。
@configuration @enableauthorizationserverpublic class authorizationserverconfig extends authorizationserserverconfigureradapter {@autowired private AuthenticationManager AuthenticationManager; @Autowired Private RedisconnectionFactory ConnectionFactory; @bean public redistokenstore tokenstore(){return new redistokenstore(connectionfactory); } @Override public void configure(authrizationserverendpointsconfigurer endpoints)throws {endpoints .authenticationmanager(authenticationmanager).tokenstore(tokenstore()); } @Override public void configure(authorizationserversecurityconfigurer security)throws exception {security .tokenkeyaccess( "permitall()").cecktokenAccess( "isauthenticated()"); } @Override public void configure(clientDetailsSserviceConfigurer Client)shlews {client.inmemory().withclient( "android").scopes( "xx")//ここには役に立たない、あなたは.secret( "android").autherizedtypes "" "" "priden .and().withclient( "webapp").scopes( "xx").authorizedgranttypes( "Implicit"); }}2.2リソースサービスの構成
auth-serverユーザー情報を提供するため、 auth-serverもResource Serverです
@configuration @enableresourceerverpublic class resourceserverconfig extends resourcesererverconfigureradapter {@override public void configure(httpsecurity http)スロー例外{http .csrf()。 respons.senderror(httpservletresponse.sc_unauthorized))。 }} @RestControllerPublic Class usercontroller {@getMapping( "/user")public principalユーザー(校長ユーザー){return user; }}2.3セキュリティ構成
@configurationPublic class securityconfig extends websecurityconfigurerAdapter {@bean public userdetailsService userdetailsservice(){return new domainuserdetailsservice(); } @bean publice passwordencoder passwordencoder(){return new bcryptpasswordencoder(); } @Override Protected void Configure(AuthenticationManagerBuilder auth)スロー例外{auth .userdetailsservice(userdetailsservice()).passwordencoder(passhipencoder()); } @Bean Public SecurityEvaluationContextExtension SecurityEvaluationContextension(){return new SecurityEvaluationContextension(); } //パスワードなしgrant_type @override @bean public AuthenticationManager AuthenticationManagerbean()Throws Exception {return super.authenticationmanagerbean(); }}2.4許可設計
用户(SysUser)角色(SysRole) sysrole)权限(SysAuthotity)設定は多对多です。 DomainUserDetailsServiceを介してユーザーとアクセス許可をロードします。
2.5構成
スプリング:プロファイル:Active:$ {spring_profiles_active:dev}アプリケーション:name:auth-server JPA:open-in-view:true database:postgresql show-sql:true hibernate:ddl-auto:uppdate datasource:プラットフォーム:Postgres URL:JDBC:PostgresQL://192.192.16.1.140ユーザー名:Wangパスワード:Yunfei Driver-Class-Name:org.postgresql.Driver Redis:Host:192.168.1.140Server:Port:9999Eureka:Client:ServiceUrl:DefaultZone: http:// $ {eureka.host:localhost}:$ {eureka.port:8761}/eureka/logging.level.org.org.org.org.org.org.org.org.springframework.security:debuglogging.leve.org.springframework:dabug#oauth2:oauth2:oauth2:oauth2:oauth2:oauth2:32.6テストデータ
2人のユーザーがdata.sql admin > ROLE_ADMIN > query_demo 、 wyf > ROLE_USERで初期化されます
3.注文サービス
3.1リソースサービスの構成
@configuration @enableresourceerverpublic class resourceserverconfig extends resourcesererverconfigureradapter {@override public void configure(httpsecurity http)スロー例外{http .csrf()。 respons.senderror(httpservletresponse.sc_unauthorized))。 }}3.2ユーザー情報構成
order-service認証と承認にauth-server使用するシンプルなマイクロサービスです。構成ファイルでは、 auth-serverアドレスでユーザー情報を指定できます。
セキュリティ:OAUTH2:リソース:ID:Order-Service user-info-uri:http:// localhost:8080/uaa/user firet-token-info:false
3.3許可テストコントローラー
アクセスはquery-demoのないauthority 、つまりadminユーザーでアクセスできます
@RestControllerPublic Class DemoController {@getMapping( "/demo")@preauthorize( "hasauthority( 'query-demo')")public string getdemo(){return "good"; }}4 Api-Gateway
api-gatewayには、この例には2つの機能があります。
implicit使用してください4.1 CSRFをオフにし、OAUTH2クライアントサポートを有効にします
@configuration @enabableouth2ssopublic class securityconfig extends websecurityconfigureradapter {@override保護されたvoid configure(httpsecurity http)スロー例外{http.csrf()。 }}4.2構成
Zuul:routes:uaa:path:/uaa/** sensitiveheaders:serviceId:auth-server order:path:/order/** sensitiveheaders:serviceID:serviceID:Order-service add-proxy-headers:grueSecurity:oauth2:client:client:access-token-uri:http:// localhost:8080/uaa/oauth/ http:// localhost:8080/uaa/oauth/authorize client-id:webappリソース:user-info-uri:http:// localhost:8080/uaa/user firet-token-info:false
5デモ
5.1クライアントコール
Postmanを使用して、 http://localhost:8080/uaa/oauth/tokenにリクエストを送信してaccess_token ( 7f9b54d4-fd25-4a2c-a848-ddf8f119230bなどの管理者ユーザー向け)
管理者ユーザー
WYFユーザー
5.2 API-GatewayのWebAppコール
まだテストは行われていません。次回は追加します。
6ソースコードアドレス
https://github.com/wiselyman/uaa-zuul
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。