Spring Cloud 에서 OAUTH2 여러 마이크로 서비스에 대한 통합 인증 및 승인을 구현해야합니다. 중앙 인증 및 승인을 위해 특정 유형의 grant type OAUTH服务로 보내면 access_token 얻어집니다. 이 토큰은 다른 마이크로 서비스에 의해 신뢰됩니다. 후속 액세스에 access_token 사용할 수 있으므로 마이크로 서비스에 대한 통합 인증 및 승인을 실현할 수 있습니다.
이 예제는 네 가지 주요 부분을 제공합니다.
discovery-service : 서비스 등록 및 발견을위한 기본 모듈auth-server : OAUTH2 인증 및 인증 센터order-service : 일반 마이크로 서비스, 인증 및 승인을 확인하는 데 사용됩니다.api-gateway : Border Gateway (모든 마이크로 서비스가 뒤에 있습니다)OAUTH2의 역할 :
Resource Server : 액세스 권한이있는 리소스Authotization Server : OAUTH2 인증 인증 센터Resource Owner : 사용자Client : API를 사용하는 클라이언트 (예 : Android, iOS, 웹 앱)보조금 유형 :
Authorization Code : 서버 응용 프로그램간에 사용됩니다Implicit : 모바일 앱 또는 웹 앱에 사용됩니다 (이 앱은 사용자의 장치에 있습니다. 예 : 인증 및 승인을 위해 휴대 전화에서 WeChat을 조절 함)Resource Owner Password Credentials(password) : 응용 프로그램은 직접 신뢰할 수 있으며 (모두 회사가 개발 했으며이 예제가 사용됩니다.Client Credentials : 응용 프로그램 API 액세스에 사용됩니다.1. 기본 환경
Postgres 계정 저장소로 사용하고, Token Storage로 Redis 사용하고 docker-compose 사용하여 서버에서 Postgres 및 Redis 시작하십시오.
redis : image : sameersbn/redis : - 최신 포트 : - "6379 : 6379"볼륨 : -/srv/docker/redis :/var/lib/redis : z Respart : AlwaysPostgresql : Always image : sameersbn/postgresql : 9.6-2 포트 : "5432 : 5432"환경 : wang : wang. -db_pass = yunfei -db_name = 주문 볼륨 : -/srv/docker/postgresql :/var/lib/postgresql : z
2. 서버
2.1 OAUTH2 서비스 구성
Redis token 보관하는 데 사용됩니다. 서비스가 다시 시작된 후에는 token 다시 구할 필요가 없습니다.
@configuration @enableAuthorizationSeRverVublic Class AuthorizationSeRizeRverConfig 확장어 승인자 erververConfigurerAdapter {@autowired private authenticationManager authenticationManager; @autowired private readisconnectionfactory connectionFactory; @bean public redistokenstore tokenstore () {return new redistokenstore (ConnectionFactory); } @override public void configure (AuthorizationServerEndPointSconfigurer endpoints) 예외 {endPoints .AuthenticaticManager (authenticaticManager) .tokenstore (tokenstore ()); } @override public void configure (AwrowizationSeRverseCurityConfiger Security) 예외 {security .tokenKeyAccess ( "permitAll ()) .checkTokenAccess ("isauthenticated () "); } @override public void configure (clientDetailsServiceConfigurer 클라이언트)는 예외 {clients.inmemory () .withCopes ( "android") .Scopes ( "xx") // 여기서 스코프가 쓸모없고, secret ( "android")를 설정할 수 있습니다. .dand () .withClient ( "webapp") .Scopes ( "xx") .AuthorizedGrantTypes ( "missplicit"); }}2.2 리소스 서비스 구성
auth-server 사용자 정보를 제공하므로 auth-server Resource Server 이기도합니다.
@configuration @enableResourcesErverVublic Class ResourceserVerConfig 확장 russerErverConfigurerAdapter {@override public void configure (httpsecurity http)는 예외를 {http .csrf (). disable () .ExceptionEticalTryPoint ((요청, 응답) ->. Response.SendError (httpservletResponse.sc_unauthorized)). 및 () .authorizeRequests () .AnyRequest (). authentated (). and () .httpbasic (); }} @RestControllerPublic Class UserController {@getMapping ( "/User") public Principal User (Principal User) {return User; }}2.3 보안 구성
@ConfigurationPublic Class SecurityConfig 확장 websecurityConfigurerAdapter {@bean public userDetailSService userDetailSService () {return new domainUserDetailSservice (); } @bean public parbliceNcoder passwordEncoder () {return new bcryptpasswordencoder (); } @override protected void configure (authenticationManagerBuilder Auth)는 예외 {auth .userdetailsService (userDetailsService ()) .PasseWordEncoder (passwordEncoder ()); } @Bean Public SecurityEvaluationContexTeention SecurityEvaluationContexTextension () {return new SecurityEvaluationContexTextension (); } // 비밀번호 없음 grant_type @override @bean public authenticationManager AuthenticationManagerBean ()이 예외 {return super.AuthenticationManagerBean (); }}2.4 허가 설계
用户(SysUser)角色(SysRole) sysrole)权限(SysAuthotity) 설정은多对多입니다. DomainUserDetailsService 를 통해 사용자 및 권한을로드하십시오.
2.5 구성
스프링 : 프로파일 : Active : $ {spring_profiles_active : dev} 응용 프로그램 : 이름 : Auth-Server JPA : Open-In-View : True Database : PostgreSQL Show-SQL : True Hibernate : DDL-Auto : DataSource : Postgres URL : JDBC : JDBC : //192.168.140 : 540 : 540 : 540 : 540 : 540 : Wang 비밀번호 : Yunfei 드라이버 클래스-이름 : org.postgresql.driver redis : host : 192.168.1.140Server : 포트 : 9999eureka : client : serviceurl : defaultzone : http : // $ {eureka.host:localhost} : $ {eureka.port : 8761} /eureka/logging.level.org.springframework.security : debuglogging.leve.org.springframework : 매우 중요한 보안 : OAUTHCE : 리소스 : 파일터-: 3.2.6 테스트 데이터
두 사용자는 data.sql admin > ROLE_ADMIN > query_demo , wyf > ROLE_USER 에서 초기화됩니다.
3. 주문 서비스
3.1 리소스 서비스 구성
@configuration @enableResourcesErverVublic Class ResourceserVerConfig 확장 russerErverConfigurerAdapter {@override public void configure (httpsecurity http)는 예외를 {http .csrf (). disable () .ExceptionEticalTryPoint ((요청, 응답) ->. Response.SendError (httpservletResponse.sc_unauthorized)). 및 () .authorizeRequests () .AnyRequest (). authentated (). and () .httpbasic (); }}3.2 사용자 정보 구성
order-service 인증 및 승인을 위해 auth-server 사용하는 간단한 마이크로 서비스입니다. 구성 파일에서 auth-server 주소로 사용자 정보를 지정할 수 있습니다.
보안 : OAUTH2 : 리소스 : ID : 주문 서비스 사용자 Info-URI : http : // localhost : 8080/UAA/User Preferoke-Token-Info : False
3.3 권한 테스트 컨트롤러
액세스는 query-demo 없이 authority 으로 액세스 할 수 있습니다 admin
@RestControllerPublic 클래스 DemoController {@getMapping ( "/demo") @preauthorize ( "hasauthority ( 'query-demo')") public String getDemo () {return "good"; }}4 API 게이트 웨이
api-gateway 에는이 예제에는 두 가지 기능이 있습니다.
implicit 사용4.1 CSRF를 끄고 OAUTH2 클라이언트 지원을 활성화하십시오
@configuration @enableoauth2ssopublic class securityconfig를 확장합니다. }}
4.2 구성
Zuul : UAA : UAA : PATH :/UAA/** 민감한 헤더 : ServiceID : Auth-Server Order : PATH :/ORDER/** 민감한 헤드러 : ServiceID : Order-Service Add-Proxy-Headers : Truesecurity : OAUTH2 : 클라이언트 : Access-Token-uri : // LocalHost : 8080/OAUC/OAUTH/OAUTH/OAUTORICIATION/OAUCHOUTIOND/OAUTHINATION/OAUST. http : // localhost : 8080/uaa/oauth/client-id : webapp resource : user-info-uri : http : // localhost : 8080/uaa/user preferoke-token-info : false
5 데모
5.1 클라이언트 전화
Postman 7f9b54d4-fd25-4a2c-a848-ddf8f119230b 하여 http://localhost:8080/uaa/oauth/token 에 요청을 보내십시오 access_token
관리자
WYF 사용자
5.2 API-Gateway의 WebApp 호출
아직 테스트가 수행되지 않았으며 다음에 추가하겠습니다.
6 소스 코드 주소
https://github.com/wiselyman/uaa-zuul
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.