Spring Cloud 에서 OAUTH 2 인증 권한 수 여 를 바탕 으로 하 는 실현 예시

9942 단어 SpringCloudOAUTH2
Spring Cloud에서 여러 개의 마이크로 서비스의 통일 인증 권한 수 여 를 실현 하기 위해OAUTH2특정한 유형의OAUTH 에 집중 인증 과 권한 수 여 를 보 내 서grant type를 받 아야 한다.이 token 은 다른 마이크로 서비스의 신뢰 를 받 아 우리 가 후속 방문access_token을 통 해 진행 할 수 있 고 마이크로 서비스의 통일 인증 권한 수 여 를 실현 했다.
이 예 는 네 부분 을 제공 했다.
  • access_token:서비스 등록 과 발견 의 기본 모듈
  • discovery-service:OAUTH 2 인증 권한 수여 센터
  • auth-server:일반 마이크로 서 비 스 는 인증 과 권한 수 여 를 검증 하 는 데 사용 된다
  • order-service:경계 게 이 트 웨 이(모든 마이크로 서 비 스 는 그 다음)
  • OAUTH 2 의 캐릭터:
  • api-gateway:권한 을 수 여 받 아 방문 한 자원
  • Resource Server:OAUTH 2 인증 권한 수여 센터
  • Authotization Server:사용자
  • Resource Owner:API 를 사용 하 는 클 라 이언 트(예 를 들 어 Android,IOS,web app)
  • Grant Type:
  • Client:서버 응용 사이 에 사용
  • Authorization Code:모 바 일 앱 이나 웹 앱(이 앱 들 은 사용자 의 장치 에 사 용 됩 니 다.예 를 들 어 핸드폰 에서 위 챗 을 올 려 인증 권한 을 부여 합 니 다)
  • Implicit:응용 은 모두 신뢰 를 받는다(모두 한 회사 가 개발 한 것 이 고 본 사례 는 사용
  • Resource Owner Password Credentials(password):응용 API 에 접근 합 니 다.
  • 1.기초 환경
    사용Client Credentials을 계 정 으로 저장 하고PostgresRedis으로 저장 하 며 사용Token을 서버 에서 시작docker-composePostgres합 니 다.
    
    Redis:
     image: sameersbn/redis:latest
     ports:
     - "6379:6379"
     volumes:
     - /srv/docker/redis:/var/lib/redis:Z
     restart: always
    
    PostgreSQL:
     restart: always
     image: sameersbn/postgresql:9.6-2
     ports:
     - "5432:5432"
     environment:
     - DEBUG=false
    
     - DB_USER=wang
     - DB_PASS=yunfei
     - DB_NAME=order
     volumes:
     - /srv/docker/postgresql:/var/lib/postgresql:Z
    2.auth-server
    2.1 OAuth 2 서비스 설정Redis저장Redis에 사용 되 며 서비스 가 재 개 되면 다시 가 져 올 필요 가 없습니다token.
    
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
     @Autowired
     private AuthenticationManager authenticationManager;
     @Autowired
     private RedisConnectionFactory connectionFactory;
    
    
     @Bean
     public RedisTokenStore tokenStore() {
      return new RedisTokenStore(connectionFactory);
     }
    
    
     @Override
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints
        .authenticationManager(authenticationManager)
        .tokenStore(tokenStore());
     }
    
     @Override
     public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
      security
        .tokenKeyAccess("permitAll()")
        .checkTokenAccess("isAuthenticated()");
     }
    
     @Override
     public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory()
        .withClient("android")
        .scopes("xx") //   scopes    ,      
        .secret("android")
        .authorizedGrantTypes("password", "authorization_code", "refresh_token")
       .and()
        .withClient("webapp")
        .scopes("xx")
        .authorizedGrantTypes("implicit");
     }
    }
    2.2 리 소스 서비스 설정token사용자 정 보 를 제공 하기 때문에auth-server도 하나auth-server
    
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
     @Override
     public void configure(HttpSecurity http) throws Exception {
      http
        .csrf().disable()
        .exceptionHandling()
        .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
       .and()
        .authorizeRequests()
        .anyRequest().authenticated()
       .and()
        .httpBasic();
     }
    }
    
    
    @RestController
    public class UserController {
    
     @GetMapping("/user")
     public Principal user(Principal user){
      return user;
     }
    }
    
    2.3 보안 설정
    
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    
     @Bean
     public UserDetailsService userDetailsService(){
      return new DomainUserDetailsService();
     }
    
     @Bean
     public PasswordEncoder passwordEncoder() {
      return new BCryptPasswordEncoder();
     }
    
     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth
        .userDetailsService(userDetailsService())
        .passwordEncoder(passwordEncoder());
     }
    
     @Bean
     public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
      return new SecurityEvaluationContextExtension();
     }
    
     //     password grant_type
     @Override
     @Bean
     public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
     }
    
    }
    2.4 권한 설계Resource Server (SysUser) (SysRole)설정 을 사용 하고 서로 간 의 관 계 는 (SysAuthotity)입 니 다. 을 통 해 사용자 와 권한 을 불 러 옵 니 다.
    2.5 설정
    
    spring:
     profiles:
     active: ${SPRING_PROFILES_ACTIVE:dev}
     application:
      name: auth-server
    
     jpa:
     open-in-view: true
     database: POSTGRESQL
     show-sql: true
     hibernate:
      ddl-auto: update
     datasource:
     platform: postgres
     url: jdbc:postgresql://192.168.1.140:5432/auth
     username: wang
     password: yunfei
     driver-class-name: org.postgresql.Driver
     redis:
     host: 192.168.1.140
    
    server:
     port: 9999
    
    
    eureka:
     client:
     serviceUrl:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
    
    
    
    logging.level.org.springframework.security: DEBUG
    
    logging.leve.org.springframework: DEBUG
    
    ##   
    security:
     oauth2:
     resource:
      filter-order: 3
    2.6 테스트 데이터DomainUserDetailsService에서 두 사용자 초기 화data.sql->admin->ROLE_ADMIN,query_demo->wyf3.order-service
    3.1 리 소스 서비스 설정
    
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter{
    
     @Override
     public void configure(HttpSecurity http) throws Exception {
      http
        .csrf().disable()
        .exceptionHandling()
        .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
       .and()
        .authorizeRequests()
        .anyRequest().authenticated()
       .and()
        .httpBasic();
     }
    }
    3.2 사용자 정보 설정ROLE_USER는 간단 한 마이크로 서비스 로order-service를 사용 하여 인증 권한 을 부여 합 니 다.설정 파일 에서 사용자 정보auth-server의 주 소 를 지정 하면 됩 니 다.
    
    security:
     oauth2:
     resource:
      id: order-service
      user-info-uri: http://localhost:8080/uaa/user
      prefer-token-info: false
    3.3 권한 테스트 컨트롤 러auth-serverauthority의 재능 을 갖 춘 방문,즉query-demo사용자
    
    @RestController
    public class DemoController {
     @GetMapping("/demo")
     @PreAuthorize("hasAuthority('query-demo')")
     public String getDemo(){
      return "good";
     }
    }
    4 api-gatewayadmin본 사례 에서 두 가지 역할 을 한다.
  • 자체 가 client 로 서 사용api-gateway
  • 외부 app 으로 접근 하 는 방향 에이전트
  • 4.1 csrf 를 닫 고 Oauth 2 client 지원 열기
    
    @Configuration
    @EnableOAuth2Sso
    public class SecurityConfig extends WebSecurityConfigurerAdapter{
     @Override
     protected void configure(HttpSecurity http) throws Exception {
    
      http.csrf().disable();
     }
    }
    4.2 설정
    
    zuul:
     routes:
     uaa:
      path: /uaa/**
      sensitiveHeaders:
      serviceId: auth-server
     order:
      path: /order/**
      sensitiveHeaders:
      serviceId: order-service
     add-proxy-headers: true
    
    security:
     oauth2:
     client:
      access-token-uri: http://localhost:8080/uaa/oauth/token
      user-authorization-uri: http://localhost:8080/uaa/oauth/authorize
      client-id: webapp
     resource:
      user-info-uri: http://localhost:8080/uaa/user
      prefer-token-info: false
    시연
    5.1 클 라 이언 트 호출implicit을 사용 하여Postman에 요청 을 보 내 면http://localhost:8080/uaa/oauth/token(admin 사용자 의 경우access_token관리자 사용자



    wyf 사용자



    5.2 api-gateway 의 웹 앱 호출
    잠시 테스트 를 하지 않 았 으 니 다음 에 보충 하 겠 습 니 다.
    6 소스 주소
    https://github.com/wiselyman/uaa-zuul
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기