SpringCloudAlibaba+Zuul+OAuth2 (三) 搭建Zuul網關微服務

前面已經搭建了資源認證服務auth 遊戲服務game-service 但是現在面臨3個問題:

  1. 安全處理和業務邏輯在一起 增加了微服務的複雜性和變更成本
  2. 隨着業務節點的增加 認證服務器壓力增大 現在服務都是需要請求auth服務來驗證token
  3. 多個微服務同時暴露 增加了外部訪問的複雜性

      綜上所述 我們採用JWT+Zuul來實現認證授權 JWT改造也很簡單 參考Oauth認證服務器第一篇搭建:https://blog.csdn.net/qq_38723394/article/details/107072233 番外篇配置一下就可以了!

1.搭建Zuul網關微服務 添加依賴 啓動類添加 @EnableZuulProxy註解

    <!--spring-boot版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>

    
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
     </dependency>

   <!--整合zuul-->
    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
   <!--整合oauth2-->
     <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>

 <dependencyManagement>
        <dependencies>
            <!--整合spring cloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--整合spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.網關yml添加配置

zuul:
  routes:
    token:
      url: http://localhost:8088        #oauth
    game:
      url: http://localhost:8181        #game-service
    gameApi:                            
      url: http://localhost:6000        #game-api 後面新建得微服務
  # 設置轉發頭 敏感信息爲null
  sensitive-headers:
security:
  oauth2:
    #身份認證信息
    client:
      client-id: gateway_client
      client-secret: 123456
    resource:
      jwt:
        #告訴網關在哪裏去拿jwt key
        key-uri: http://localhost:8088/oauth/token_key  #org.springframework.security.oauth2.provider.endpoint.TokenKeyEndpoint

3.編寫配置文件

/**
 * @Description 網關資源認證配置
 * @Date 2020/6/24 16:43
 * @Author Jax
 */
@Configuration
@EnableResourceServer
public class ZuulSecurityConfig extends ResourceServerConfigurerAdapter {

    /**
    * 如果對安全校驗不是很高得話,可以不配置這個 默認叫oauth2-resource 
    **/
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .resourceId("gateway");
    }

    /**
     * 配置除了 獲取token 不需要認證 其他請求都需要認證
     * 根據自己得項目情況做配置 我這裏是yml文件配置了前綴/token這個url是用來訪問認證服務器 
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new ZuulAuditLogFilter(), ExceptionTranslationFilter.class)
                .authorizeRequests()
                .antMatchers("/token/**").permitAll()
                .anyRequest().authenticated();
    }
}

4.做好上面得配置 下面我們新建一個springboot maven項目 game-api 相關依賴如下

<!--spring-boot 版本-->
<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.2.5.RELEASE</version>
</parent>
 
<!--spring-cloud  spring cloud alibaba版本-->
 
<dependencyManagement>
        <dependencies>
            <!--整合spring cloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--整合spring cloud alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>
 
 
<!--整合oauth2-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
 
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

game-api yml 添加配置

server:
  port: 6000
spring:
  application:
    name: game-api
security:
  oauth2:
    client:
      client-id: api_client
      client-secret: 123456
    resource:
      jwt:
        key-uri: http://localhost:8088/oauth/token_key

數據庫 拷貝一條數據 client_id改名叫game-api

INSERT INTO `oauth_client_details`(`client_id`, `resource_ids`, `client_secret`, `scope`, `authorized_grant_types`, `web_server_redirect_uri`, `authorities`, `access_token_validity`, `refresh_token_validity`, `additional_information`, `autoapprove`) VALUES ('api_client', 'gateway,game-api', '$2a$10$HT1fF.8WhP08YblPWphCMeuzJM7AP68LR86uC/kX9tbXIHOxBbkMW', 'read,write', 'password', 'http://127.0.0.1', 'ROLE_PROJECT_ADMIN', 7200, 1800, NULL, 'true');

編寫game-api配置文件

@Configuration
@EnableResourceServer
public class OAuthResourceServiceConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("game-api");
    }

  
}

編寫一個controller 來獲取當前用戶 

@GetMapping("/user/test")
public String getUserMsg(@AuthenticationPrincipal String username){
    System.out.println("------->>>獲取到的用戶username="+username);
    return username;
}

OK 依次啓動oauth , gateway ,game-api 一定要先啓動oauth 現在網關啓動 要先去認證服務器獲取jwt key

獲取令牌 進行訪問  搞定!

6.測試 獲取token 及使用token獲取用戶信息

獲取當前用戶信息測試結果

至此 集成網關Zuul實現認證 完成~!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章