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网关里面的配置里声明了需要指定角色才可以访问,因此需要账户拥有指定角色,才能访问