zuul網關集成Ouath2.0請求放行,授權碼驗證,角色驗證

zuul網關集成Ouath2.0請求放行,授權碼驗證,角色驗證、

1. 環境介紹
本篇文章是在我的上一篇文章上環境上進行的,
Ouath2.0在SpringCloud下驗證獲取授權碼

本文不主要介紹SpringCloud環境配置

2. zuul網關
項目工程目錄圖
在這裏插入圖片描述
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.fenghua</groupId>
    <artifactId>tm_springcloud_zuul_service</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    <!-- 管理依賴 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M7</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <!-- SpringBoot整合eureka客戶端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <!-- springboot整合freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!-->spring-boot 整合security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
    </dependencies>
    <!-- 注意: 這裏必須要添加, 否者各種依賴有問題 -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

application.yml

server:
  port: 81
###註冊 中心
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8100/eureka
###網關名稱
spring:
  application:
    name: tm-fenghua-zuul

#### 配置網關反向代理
zuul:
  host:
    connect-timeout-millis: 10000
    socket-timeout-millis: 10000
  routes:
    api-a:
      ### 以 /api-member/訪問轉發到用戶服務
      path: /api-user/**
      serviceId: tm-fenghua-user
    api-b:
      ### 以 /api-commodity/訪問轉發到商品服務
      path: /api-commodity/**
      serviceId: tm-fenghua-commodity
ribbon:
  eureka:
    enabled: true
  OkToRetryOnAllOperations: false #對所有操作請求都進行重試,默認false
  ReadTimeout: 8000   #指的是建立連接所用的時間,,默認值5000
  ConnectTimeout: 10000 #指的是建立連接後從服務器讀取到可用資源所用的時間,默認值2000
  MaxAutoRetries: 0     #對當前實例的重試次數,默認0
  MaxAutoRetriesNextServer: 1 #對切換實例的重試次數,默認1
hystrix:
  command:
    default:  #default全局有效,service id指定應用有效
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            timeoutInMilliseconds: 10000 #斷路器超時時間,默認1000ms

security:
  oauth2:
    resource:
      ####從認證授權中心上驗證token
      tokenInfoUri: http://localhost:8500/oauth/check_token
      preferTokenInfo: true
    client:
      accessTokenUri: http://localhost:8500/oauth/token
      userAuthorizationUri: http://localhost:8500/oauth/authorize
      ###appid
      clientId: guiyang_university
      ###appSecret
      clientSecret: 123456

AppZuul類

package com.tm.zuul;


import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableSwagger2Doc
@EnableHystrix
@EnableOAuth2Sso
public class AppZuul {

    public static void main(String[] args) {
        SpringApplication.run(AppZuul.class, args);
    }
}

SwaggerDocumentationConfig類

package com.tm.zuul.config;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

 // 添加文檔來源
@Component
@Primary
public class SwaggerDocumentationConfig implements SwaggerResourcesProvider {

    @Override
    public List<SwaggerResource> get() {
        List resources = new ArrayList<>();
        resources.add(swaggerResource("tm-fenghua-user", "/api-user/v2/api-docs", "1.0"));
        resources.add(swaggerResource("tm-fenghua-commodity", "/api-commodity/v2/api-docs", "1.0"));
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}

ResourceServerConfiguration類

package com.tm.zuul.config.ouath2;

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 {

    // @EnableResourceServer 開啓資源服務中心
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 請求進行攔截 驗證 accessToken
        http.authorizeRequests()
        		//需要驗證授權碼成功並且爲SuperAdmin角色才能調用該接口
                .antMatchers("/api-commodity/commodity/addOrder").hasAnyAuthority("SuperAdmin")
                //需要驗證授權碼成功並且爲SuperStart角色才能調用該接口
                .antMatchers("/api-commodity/commodity/removeOrder").hasAnyAuthority("SuperStart")
               	//放行
                .antMatchers(
                        //Swagger-網關
                        "/swagger-ui.html",
                        "/webjars/**",
                        "/v2/**",
                        "/swagger-resources/**",
                        //Swagger-用戶
                        "/api-user/swagger-ui.html",
                        "/api-user/webjars/**",
                        "/api-user/v2/**",
                        "/api-user/swagger-resources/**",
                        //Swagger-商品
                        "/api-commodity/swagger-ui.html",
                        "/api-commodity/webjars/**",
                        "/api-commodity/v2/**",
                        "/api-commodity/swagger-resources/**",
                        //用戶註冊
                        "/api-user/storeUser/storeUserRegister",
                        //用戶登錄
                        "/api-user/storeUser/storeUserLogin"
                ).permitAll()
                //攔截其他所有請求
                .anyRequest().authenticated()
                .and().csrf().disable();
    }
}

3. 資源服務關鍵代碼

package com.tm.commodity.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/commodity")
public class CommodityController {

	@GetMapping("/queryOrder")
	public String queryOrder() {
		return "queryOrder";
	}

	@GetMapping("/addOrder")
	public String addOrder() {
		return "addOrder";
	}

	@GetMapping("/removeOrder")
	public String removeOrder() {
		return "removeOrder";
	}

}

4. 演示效果
先獲取授權碼
在這裏插入圖片描述
驗證Token
在這裏插入圖片描述
擁有Admin與SuperAdmnin角色
將驗證碼放入Swagger裏面
在這裏插入圖片描述
請求接口
addOrder
在這裏插入圖片描述
removeOrder接口
在這裏插入圖片描述
因爲我們在Zuul網關裏面的配置裏聲明瞭需要指定角色纔可以訪問,因此需要賬戶擁有指定角色,才能訪問

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