欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Cloud Gateway 实现Token校验

程序员文章站 2022-04-14 16:19:57
在我看来,在某些场景下,网关就像是一个公共方法,把项目中的都要用到的一些功能提出来,抽象成一个服务。比如,我们可以在业务网关上做日志收集、Token校验等等,当然这么理解很狭隘,因为网关的能力远不止如此,但是不妨碍我们更好地理解它。下面的例子演示了,如何在网关校验Token,并提取用户信息放到Hea ......

在我看来,在某些场景下,网关就像是一个公共方法,把项目中的都要用到的一些功能提出来,抽象成一个服务。比如,我们可以在业务网关上做日志收集、token校验等等,当然这么理解很狭隘,因为网关的能力远不止如此,但是不妨碍我们更好地理解它。下面的例子演示了,如何在网关校验token,并提取用户信息放到header中传给下游业务系统。

1. 生成token

用户登录成功以后,生成token,此后的所有请求都带着token。网关负责校验token,并将用户信息放入请求header,以便下游系统可以方便的获取用户信息。

Spring Cloud Gateway 实现Token校验

Spring Cloud Gateway 实现Token校验

为了方便演示,本例中涉及三个工程

公共项目:cjs-commons-jwt

认证服务:cjs-auth-service

网关服务:cjs-gateway-example

1.1. token生成与校验工具类

因为生成token在认证服务中,token校验在网关服务中,因此,我把这一部分写在了公共项目cjs-commons-jwt中

pom.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 4   xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelversion>4.0.0</modelversion>
 6 
 7     <groupid>com.cjs.example</groupid>
 8     <artifactid>cjs-commons-jwt</artifactid>
 9     <version>1.0-snapshot</version>
10 
11     <properties>
12         <project.build.sourceencoding>utf-8</project.build.sourceencoding>
13         <maven.compiler.source>1.8</maven.compiler.source>
14         <maven.compiler.target>1.8</maven.compiler.target>
15     </properties>
16 
17     <dependencies>
18         <dependency>
19             <groupid>com.auth0</groupid>
20             <artifactid>java-jwt</artifactid>
21             <version>3.10.0</version>
22         </dependency>
23         <dependency>
24             <groupid>org.apache.commons</groupid>
25             <artifactid>commons-lang3</artifactid>
26             <version>3.9</version>
27         </dependency>
28         <dependency>
29             <groupid>com.alibaba</groupid>
30             <artifactid>fastjson</artifactid>
31             <version>1.2.66</version>
32         </dependency>
33     </dependencies>
34 
35 </project>

jwtutil.java

 1 package com.cjs.example.utils;
 2 
 3 import com.auth0.jwt.jwt;
 4 import com.auth0.jwt.jwtverifier;
 5 import com.auth0.jwt.algorithms.algorithm;
 6 import com.auth0.jwt.exceptions.jwtdecodeexception;
 7 import com.auth0.jwt.exceptions.signatureverificationexception;
 8 import com.auth0.jwt.exceptions.tokenexpiredexception;
 9 import com.auth0.jwt.interfaces.decodedjwt;
10 import com.cjs.example.enums.responsecodeenum;
11 import com.cjs.example.exception.tokenauthenticationexception;
12 
13 import java.util.date;
14 
15 /**
16  * @author chengjiansheng
17  * @date 2020-03-08
18  */
19 public class jwtutil {
20 
21     public static final long token_expire_time = 7200 * 1000;
22     private static final string issuer = "cheng";
23 
24     /**
25      * 生成token
26      * @param username 用户标识(不一定是用户名,有可能是用户id或者手机号什么的)
27      * @param secretkey
28      * @return
29      */
30     public static string generatetoken(string username, string secretkey) {
31         algorithm algorithm = algorithm.hmac256(secretkey);
32         date now = new date();
33         date expiretime = new date(now.gettime() + token_expire_time);
34 
35         string token = jwt.create()
36                 .withissuer(issuer)
37                 .withissuedat(now)
38                 .withexpiresat(expiretime)
39                 .withclaim("username", username)
40                 .sign(algorithm);
41 
42         return token;
43     }
44 
45     /**
46      * 校验token
47      * @param token
48      * @param secretkey
49      * @return
50      */
51     public static void verifytoken(string token, string secretkey) {
52         try {
53             algorithm algorithm = algorithm.hmac256(secretkey);
54             jwtverifier jwtverifier = jwt.require(algorithm).withissuer(issuer).build();
55             jwtverifier.verify(token);
56         } catch (jwtdecodeexception jwtdecodeexception) {
57             throw new tokenauthenticationexception(responsecodeenum.token_invalid.getcode(), responsecodeenum.token_invalid.getmessage());
58         } catch (signatureverificationexception signatureverificationexception) {
59             throw new tokenauthenticationexception(responsecodeenum.token_signature_invalid.getcode(), responsecodeenum.token_signature_invalid.getmessage());
60         } catch (tokenexpiredexception tokenexpiredexception) {
61             throw new tokenauthenticationexception(responsecodeenum.token_expired.getcode(), responsecodeenum.token_invalid.getmessage());
62         } catch (exception ex) {
63             throw new tokenauthenticationexception(responsecodeenum.unknown_error.getcode(), responsecodeenum.unknown_error.getmessage());
64         }
65     }
66 
67     /**
68      * 从token中提取用户信息
69      * @param token
70      * @return
71      */
72     public static string getuserinfo(string token) {
73         decodedjwt decodedjwt = jwt.decode(token);
74         string username = decodedjwt.getclaim("username").asstring();
75         return username;
76     }
77 
78 }

responsecodeenum.java

 1 package com.cjs.example.enums;
 2 
 3 /**
 4  * @author chengjiansheng
 5  * @date 2020-03-08
 6  */
 7 public enum responsecodeenum {
 8 
 9     success(0, "成功"),
10     fail(-1, "失败"),
11     login_error(1000, "用户名或密码错误"),
12     unknown_error(2000, "未知错误"),
13     parameter_illegal(2001, "参数不合法"),
14     token_invalid(2002, "无效的token"),
15     token_signature_invalid(2003, "无效的签名"),
16     token_expired(2004, "token已过期"),
17     token_mission(2005, "token缺失"),
18     refresh_token_invalid(2006, "刷新token无效");
19 
20 
21     private int code;
22 
23     private string message;
24 
25     responsecodeenum(int code, string message) {
26         this.code = code;
27         this.message = message;
28     }
29 
30     public int getcode() {
31         return code;
32     }
33 
34     public string getmessage() {
35         return message;
36     }
37 
38 }

responseresult.java

 1 package com.cjs.example;
 2 
 3 import com.cjs.example.enums.responsecodeenum;
 4 
 5 /**
 6  * @author chengjiansheng
 7  * @date 2020-03-08
 8  */
 9 public class responseresult<t> {
10 
11     private int code = 0;
12 
13     private string msg;
14 
15     private t data;
16 
17     public responseresult(int code, string msg) {
18         this.code = code;
19         this.msg = msg;
20     }
21 
22     public responseresult(int code, string msg, t data) {
23         this.code = code;
24         this.msg = msg;
25         this.data = data;
26     }
27 
28     public static responseresult success() {
29         return new responseresult(responsecodeenum.success.getcode(), responsecodeenum.success.getmessage());
30     }
31 
32     public static <t> responseresult<t> success(t data) {
33         return new responseresult(responsecodeenum.success.getcode(), responsecodeenum.success.getmessage(), data);
34     }
35 
36     public static responseresult error(int code, string msg) {
37         return new responseresult(code, msg);
38     }
39 
40     public static <t> responseresult<t> error(int code, string msg, t data) {
41         return new responseresult(code, msg, data);
42     }
43 
44     public boolean issuccess() {
45         return code == 0;
46     }
47 
48     public int getcode() {
49         return code;
50     }
51 
52     public void setcode(int code) {
53         this.code = code;
54     }
55 
56     public string getmsg() {
57         return msg;
58     }
59 
60     public void setmsg(string msg) {
61         this.msg = msg;
62     }
63 
64     public t getdata() {
65         return data;
66     }
67 
68     public void setdata(t data) {
69         this.data = data;
70     }
71 }

1.2. 生成token

这一部分在cjs-auth-service中

pom.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 3          xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelversion>4.0.0</modelversion>
 5     <parent>
 6         <groupid>org.springframework.boot</groupid>
 7         <artifactid>spring-boot-starter-parent</artifactid>
 8         <version>2.2.5.release</version>
 9         <relativepath/> <!-- lookup parent from repository -->
10     </parent>
11     <groupid>com.cjs.example</groupid>
12     <artifactid>cjs-auth-service</artifactid>
13     <version>0.0.1-snapshot</version>
14     <name>cjs-auth-service</name>
15 
16     <properties>
17         <java.version>1.8</java.version>
18     </properties>
19 
20     <dependencies>
21         <dependency>
22             <groupid>org.springframework.boot</groupid>
23             <artifactid>spring-boot-starter-data-redis</artifactid>
24         </dependency>
25         <dependency>
26             <groupid>org.springframework.boot</groupid>
27             <artifactid>spring-boot-starter-web</artifactid>
28         </dependency>
29 
30         <dependency>
31             <groupid>org.apache.commons</groupid>
32             <artifactid>commons-lang3</artifactid>
33             <version>3.9</version>
34         </dependency>
35         <dependency>
36             <groupid>commons-codec</groupid>
37             <artifactid>commons-codec</artifactid>
38             <version>1.14</version>
39         </dependency>
40         <dependency>
41             <groupid>org.apache.commons</groupid>
42             <artifactid>commons-pool2</artifactid>
43             <version>2.8.0</version>
44         </dependency>
45 
46         <dependency>
47             <groupid>com.cjs.example</groupid>
48             <artifactid>cjs-commons-jwt</artifactid>
49             <version>1.0-snapshot</version>
50         </dependency>
51 
52         <dependency>
53             <groupid>org.projectlombok</groupid>
54             <artifactid>lombok</artifactid>
55             <optional>true</optional>
56         </dependency>
57     </dependencies>
58 
59     <build>
60         <plugins>
61             <plugin>
62                 <groupid>org.springframework.boot</groupid>
63                 <artifactid>spring-boot-maven-plugin</artifactid>
64             </plugin>
65         </plugins>
66     </build>
67 
68 </project>

logincontroller.java

  1 package com.cjs.example.controller;
  2 
  3 import com.cjs.example.responseresult;
  4 import com.cjs.example.domain.loginrequest;
  5 import com.cjs.example.domain.loginresponse;
  6 import com.cjs.example.domain.refreshrequest;
  7 import com.cjs.example.enums.responsecodeenum;
  8 import com.cjs.example.utils.jwtutil;
  9 import org.apache.commons.lang3.stringutils;
 10 import org.apache.tomcat.util.security.md5encoder;
 11 import org.springframework.beans.factory.annotation.autowired;
 12 import org.springframework.beans.factory.annotation.value;
 13 import org.springframework.data.redis.core.hashoperations;
 14 import org.springframework.data.redis.core.stringredistemplate;
 15 import org.springframework.validation.bindingresult;
 16 import org.springframework.validation.annotation.validated;
 17 import org.springframework.web.bind.annotation.*;
 18 
 19 import java.util.uuid;
 20 import java.util.concurrent.timeunit;
 21 
 22 /**
 23  * @author chengjiansheng
 24  * @date 2020-03-08
 25  */
 26 @restcontroller
 27 public class logincontroller {
 28 
 29     /**
 30      * apollo 或 nacos
 31      */
 32     @value("${secretkey:123456}")
 33     private string secretkey;
 34 
 35     @autowired
 36     private stringredistemplate stringredistemplate;
 37 
 38     /**
 39      * 登录
 40      */
 41     @postmapping("/login")
 42     public responseresult login(@requestbody @validated loginrequest request, bindingresult bindingresult) {
 43         if (bindingresult.haserrors()) {
 44             return responseresult.error(responsecodeenum.parameter_illegal.getcode(), responsecodeenum.parameter_illegal.getmessage());
 45         }
 46 
 47         string username = request.getusername();
 48         string password = request.getpassword();
 49         //  假设查询到用户id是1001
 50         string userid = "1001";
 51         if ("hello".equals(username) && "world".equals(password)) {
 52             //  生成token
 53             string token = jwtutil.generatetoken(userid, secretkey);
 54 
 55             //  生成刷新token
 56             string refreshtoken = uuid.randomuuid().tostring().replace("-", "");
 57 
 58             //  放入缓存
 59             hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
 60 //            hashoperations.put(refreshtoken, "token", token);
 61 //            hashoperations.put(refreshtoken, "user", username);
 62 //            stringredistemplate.expire(refreshtoken, jwtutil.token_expire_time, timeunit.milliseconds);
 63 
 64             /**
 65              * 如果可以允许用户退出后token如果在有效期内仍然可以使用的话,那么就不需要存redis
 66              * 因为,token要跟用户做关联的话,就必须得每次都带一个用户标识,
 67              * 那么校验token实际上就变成了校验token和用户标识的关联关系是否正确,且token是否有效
 68              */
 69 
 70 //            string key = md5encoder.encode(userid.getbytes());
 71 
 72             string key = userid;
 73             hashoperations.put(key, "token", token);
 74             hashoperations.put(key, "refreshtoken", refreshtoken);
 75             stringredistemplate.expire(key, jwtutil.token_expire_time, timeunit.milliseconds);
 76 
 77             loginresponse loginresponse = new loginresponse();
 78             loginresponse.settoken(token);
 79             loginresponse.setrefreshtoken(refreshtoken);
 80             loginresponse.setusername(userid);
 81 
 82             return responseresult.success(loginresponse);
 83         }
 84 
 85         return responseresult.error(responsecodeenum.login_error.getcode(), responsecodeenum.login_error.getmessage());
 86     }
 87 
 88     /**
 89      * 退出
 90      */
 91     @getmapping("/logout")
 92     public responseresult logout(@requestparam("userid") string userid) {
 93         hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
 94         string key = userid;
 95         hashoperations.delete(key);
 96         return responseresult.success();
 97     }
 98 
 99     /**
100      * 刷新token
101      */
102     @postmapping("/refreshtoken")
103     public responseresult refreshtoken(@requestbody @validated refreshrequest request, bindingresult bindingresult) {
104         string userid = request.getuserid();
105         string refreshtoken = request.getrefreshtoken();
106         hashoperations<string, string, string> hashoperations = stringredistemplate.opsforhash();
107         string key = userid;
108         string originalrefreshtoken = hashoperations.get(key, "refreshtoken");
109         if (stringutils.isblank(originalrefreshtoken) || !originalrefreshtoken.equals(refreshtoken)) {
110             return responseresult.error(responsecodeenum.refresh_token_invalid.getcode(), responsecodeenum.refresh_token_invalid.getmessage());
111         }
112 
113         //  生成新token
114         string newtoken = jwtutil.generatetoken(userid, secretkey);
115         hashoperations.put(key, "token", newtoken);
116         stringredistemplate.expire(userid, jwtutil.token_expire_time, timeunit.milliseconds);
117 
118         return responseresult.success(newtoken);
119     }
120 }

hellocontroller.java

 1 package com.cjs.example.controller;
 2 
 3 import org.springframework.web.bind.annotation.getmapping;
 4 import org.springframework.web.bind.annotation.requestheader;
 5 import org.springframework.web.bind.annotation.requestmapping;
 6 import org.springframework.web.bind.annotation.restcontroller;
 7 
 8 /**
 9  * @author chengjiansheng
10  * @date 2020-03-08
11  */
12 @restcontroller
13 @requestmapping("/hello")
14 public class hellocontroller {
15 
16     @getmapping("/sayhello")
17     public string sayhello(string name) {
18         return "hello, " + name;
19     }
20 
21     @getmapping("/sayhi")
22     public string sayhi(@requestheader("userid") string userid) {
23         return userid;
24     }
25 
26 }

application.yml

 1 server:
 2   port: 8081
 3   servlet:
 4     context-path: /auth-server
 5 spring:
 6   application:
 7     name: cjs-auth-service
 8   redis:
 9     host: 127.0.0.1
10     password: 123456
11     port: 6379
12     lettuce:
13       pool:
14         max-active: 10
15         max-idle: 5
16         min-idle: 5
17         max-wait: 5000

2. 校验token

gatewayfilter和globalfilter都可以,这里用globalfilter

pom.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 3          xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelversion>4.0.0</modelversion>
 5     <parent>
 6         <groupid>org.springframework.boot</groupid>
 7         <artifactid>spring-boot-starter-parent</artifactid>
 8         <version>2.2.5.release</version>
 9         <relativepath/> <!-- lookup parent from repository -->
10     </parent>
11     <groupid>com.cms.example</groupid>
12     <artifactid>cjs-gateway-example</artifactid>
13     <version>0.0.1-snapshot</version>
14     <name>cjs-gateway-example</name>
15 
16     <properties>
17         <java.version>1.8</java.version>
18         <spring-cloud.version>hoxton.sr1</spring-cloud.version>
19     </properties>
20 
21     <dependencies>
22         <dependency>
23             <groupid>org.springframework.boot</groupid>
24             <artifactid>spring-boot-starter-data-redis-reactive</artifactid>
25         </dependency>
26         <dependency>
27             <groupid>org.springframework.cloud</groupid>
28             <artifactid>spring-cloud-starter-gateway</artifactid>
29         </dependency>
30         <dependency>
31             <groupid>com.auth0</groupid>
32             <artifactid>java-jwt</artifactid>
33             <version>3.10.0</version>
34         </dependency>
35         <dependency>
36             <groupid>com.cjs.example</groupid>
37             <artifactid>cjs-commons-jwt</artifactid>
38             <version>1.0-snapshot</version>
39         </dependency>
40 
41 
42         <dependency>
43             <groupid>org.projectlombok</groupid>
44             <artifactid>lombok</artifactid>
45             <optional>true</optional>
46         </dependency>
47     </dependencies>
48 
49     <dependencymanagement>
50         <dependencies>
51             <dependency>
52                 <groupid>org.springframework.cloud</groupid>
53                 <artifactid>spring-cloud-dependencies</artifactid>
54                 <version>${spring-cloud.version}</version>
55                 <type>pom</type>
56                 <scope>import</scope>
57             </dependency>
58         </dependencies>
59     </dependencymanagement>
60 
61     <build>
62         <plugins>
63             <plugin>
64                 <groupid>org.springframework.boot</groupid>
65                 <artifactid>spring-boot-maven-plugin</artifactid>
66             </plugin>
67         </plugins>
68     </build>
69 
70 </project>

authorizefilter.java

 1 package com.cms.example.filter;
 2 
 3 import com.alibaba.fastjson.json;
 4 import com.cjs.example.responseresult;
 5 import com.cjs.example.enums.responsecodeenum;
 6 import com.cjs.example.exception.tokenauthenticationexception;
 7 import com.cjs.example.utils.jwtutil;
 8 import lombok.extern.slf4j.slf4j;
 9 import org.apache.commons.lang3.stringutils;
10 import org.springframework.beans.factory.annotation.autowired;
11 import org.springframework.beans.factory.annotation.value;
12 import org.springframework.cloud.gateway.filter.gatewayfilterchain;
13 import org.springframework.cloud.gateway.filter.globalfilter;
14 import org.springframework.core.ordered;
15 import org.springframework.core.io.buffer.databuffer;
16 import org.springframework.data.redis.core.stringredistemplate;
17 import org.springframework.http.httpstatus;
18 import org.springframework.http.server.reactive.serverhttprequest;
19 import org.springframework.http.server.reactive.serverhttpresponse;
20 import org.springframework.stereotype.component;
21 import org.springframework.web.server.serverwebexchange;
22 import reactor.core.publisher.flux;
23 import reactor.core.publisher.mono;
24 
25 /**
26  * @author chengjiansheng
27  * @date 2020-03-08
28  */
29 @slf4j
30 @component
31 public class authorizefilter implements globalfilter, ordered {
32 
33     @value("${secretkey:123456}")
34     private string secretkey;
35 
36 //    @autowired
37 //    private stringredistemplate stringredistemplate;
38 
39     @override
40     public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
41         serverhttprequest serverhttprequest = exchange.getrequest();
42         serverhttpresponse serverhttpresponse = exchange.getresponse();
43         string uri = serverhttprequest.geturi().getpath();
44 
45         //  检查白名单(配置)
46         if (uri.indexof("/auth-server/login") >= 0) {
47             return chain.filter(exchange);
48         }
49 
50         string token = serverhttprequest.getheaders().getfirst("token");
51         if (stringutils.isblank(token)) {
52             serverhttpresponse.setstatuscode(httpstatus.unauthorized);
53             return getvoidmono(serverhttpresponse, responsecodeenum.token_mission);
54         }
55 
56         //todo 检查redis中是否有此token
57 
58         try {
59             jwtutil.verifytoken(token, secretkey);
60         } catch (tokenauthenticationexception ex) {
61             return getvoidmono(serverhttpresponse, responsecodeenum.token_invalid);
62         } catch (exception ex) {
63             return getvoidmono(serverhttpresponse, responsecodeenum.unknown_error);
64         }
65 
66         string userid = jwtutil.getuserinfo(token);
67 
68         serverhttprequest mutablereq = serverhttprequest.mutate().header("userid", userid).build();
69         serverwebexchange mutableexchange = exchange.mutate().request(mutablereq).build();
70 
71         return chain.filter(mutableexchange);
72     }
73 
74     private mono<void> getvoidmono(serverhttpresponse serverhttpresponse, responsecodeenum responsecodeenum) {
75         serverhttpresponse.getheaders().add("content-type", "application/json;charset=utf-8");
76         responseresult responseresult = responseresult.error(responsecodeenum.getcode(), responsecodeenum.getmessage());
77         databuffer databuffer = serverhttpresponse.bufferfactory().wrap(json.tojsonstring(responseresult).getbytes());
78         return serverhttpresponse.writewith(flux.just(databuffer));
79     }
80 
81     @override
82     public int getorder() {
83         return -100;
84     }
85 }

application.yml

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5         - id: path_route
 6           uri: http://localhost:8081/auth-server/
 7           filters:
 8             - mylog=true
 9           predicates:
10             - path=/auth-server/** 

这里我还自定义了一个日志收集过滤器

 1 package com.cms.example.filter;
 2 
 3 import org.apache.commons.logging.log;
 4 import org.apache.commons.logging.logfactory;
 5 import org.springframework.cloud.gateway.filter.gatewayfilter;
 6 import org.springframework.cloud.gateway.filter.factory.abstractgatewayfilterfactory;
 7 import org.springframework.http.server.reactive.serverhttprequest;
 8 import org.springframework.stereotype.component;
 9 import reactor.core.publisher.mono;
10 
11 import java.util.arrays;
12 import java.util.list;
13 
14 /**
15  * @author chengjiansheng
16  * @date 2020-03-08
17  */
18 @component
19 public class myloggatewayfilterfactory extends abstractgatewayfilterfactory<myloggatewayfilterfactory.config> {
20 
21     private static final log log = logfactory.getlog(myloggatewayfilterfactory.class);
22     private static final string my_log_start_time = myloggatewayfilterfactory.class.getname() + "." + "starttime";
23 
24     public myloggatewayfilterfactory() {
25         super(config.class);
26     }
27 
28     @override
29     public list<string> shortcutfieldorder() {
30         return arrays.aslist("enabled");
31     }
32 
33     @override
34     public gatewayfilter apply(config config) {
35         return (exchange, chain) -> {
36             if (!config.isenabled()) {
37                 return chain.filter(exchange);
38             }
39             exchange.getattributes().put(my_log_start_time, system.currenttimemillis());
40             return chain.filter(exchange).then(mono.fromrunnable(() -> {
41                 long starttime = exchange.getattribute(my_log_start_time);
42                 if (null != starttime) {
43                     serverhttprequest serverhttprequest = exchange.getrequest();
44                     stringbuilder sb = new stringbuilder();
45                     sb.append(serverhttprequest.geturi().getrawpath());
46                     sb.append(" : ");
47                     sb.append(serverhttprequest.getqueryparams());
48                     sb.append(" : ");
49                     sb.append(system.currenttimemillis() - starttime);
50                     sb.append("ms");
51                     log.info(sb.tostring());
52                 }
53             }));
54         };
55     }
56 
57     public static class config {
58         /**
59          * 是否开启
60          */
61         private boolean enabled;
62 
63         public config() {
64         }
65 
66         public boolean isenabled() {
67             return enabled;
68         }
69 
70         public void setenabled(boolean enabled) {
71             this.enabled = enabled;
72         }
73     }
74 } 

用postman访问就能看到效果

http://localhost:8080/auth-server/hello/sayhi
http://localhost:8080/auth-server/hello/sayhello?name=aaa

Spring Cloud Gateway 实现Token校验

Spring Cloud Gateway 实现Token校验  

3. spring cloud gateway

 1 @springbootapplication
 2 public class demogatewayapplication {
 3     @bean
 4     public routelocator customroutelocator(routelocatorbuilder builder) {
 5         return builder.routes()
 6             .route("path_route", r -> r.path("/get")
 7                 .uri("http://httpbin.org"))
 8             .route("host_route", r -> r.host("*.myhost.org")
 9                 .uri("http://httpbin.org"))
10             .route("rewrite_route", r -> r.host("*.rewrite.org")
11                 .filters(f -> f.rewritepath("/foo/(?<segment>.*)", "/${segment}"))
12                 .uri("http://httpbin.org"))
13             .route("hystrix_route", r -> r.host("*.hystrix.org")
14                 .filters(f -> f.hystrix(c -> c.setname("slowcmd")))
15                 .uri("http://httpbin.org"))
16             .route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
17                 .filters(f -> f.hystrix(c -> c.setname("slowcmd").setfallbackuri("forward:/hystrixfallback")))
18                 .uri("http://httpbin.org"))
19             .route("limit_route", r -> r
20                 .host("*.limited.org").and().path("/anything/**")
21                 .filters(f -> f.requestratelimiter(c -> c.setratelimiter(redisratelimiter())))
22                 .uri("http://httpbin.org"))
23             .build();
24     }
25 }

3.1. gatewayfilter factories

路由过滤器允许以某种方式修改输入的http请求或输出的http响应。路由过滤器适用于特定路由。spring cloud gateway包括许多内置的gatewayfilter工厂。

3.1.1.  addrequestheader gatewayfilter factory 

addrequestheader gatewayfilter 采用name和value参数。 

例如:下面的例子,对于所有匹配的请求,将在下游请求头中添加 x-request-red:blue

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: add_request_header_route
6         uri: https://example.org
7         filters:
8         - addrequestheader=x-request-red, blue 

刚才说了,addrequestheader采用name和value作为参数。而uri中的变量可以用在value中,例如:

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5       - id: add_request_header_route
 6         uri: https://example.org
 7         predicates:
 8         - path=/red/{segment}
 9         filters:
10         - addrequestheader=x-request-red, blue-{segment}

3.1.2.  addrequestparameter gatewayfilter factory 

addrequestparameter gatewayfilter 也是采用name和value参数

例如:下面的例子,对于所有匹配的请求,将会在下游请求的查询字符串中添加 red=blue

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: add_request_parameter_route
6         uri: https://example.org
7         filters:
8         - addrequestparameter=red, blue

同样,addrequestparameter也支持在value中引用uri中的变量,例如:

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5       - id: add_request_parameter_route
 6         uri: https://example.org
 7         predicates:
 8         - host: {segment}.myhost.org
 9         filters:
10         - addrequestparameter=foo, bar-{segment}

3.1.3.  addresponseheader gatewayfilter factory 

addresponseheader gatewayfilter 依然采用name和value参数。不在赘述,如下:

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: add_response_header_route
6         uri: https://example.org
7         filters:
8         - addresponseheader=x-response-red, blue

3.1.4.  deduperesponseheader gatewayfilter factory 

deduperesponseheader gatewayfilter 采用一个name参数和一个可选的strategy参数。name可以包含以空格分隔的header名称列表。例如:下面的例子,如果在网关cors逻辑和下游逻辑都将它们添加的情况下,这将删除access-control-allow-credentials和access-control-allow-origin响应头中的重复值。

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: dedupe_response_header_route
6         uri: https://example.org
7         filters:
8         - deduperesponseheader=access-control-allow-credentials access-control-allow-origin

3.1.5.  prefixpath gatewayfilter factory

prefixpath gatewayfilter 只有一个prefix参数。下面的例子,对于所有匹配的请求,将会在请求url上加上前缀/mypath,因此请求/hello在被转发后的url变成/mypath/hello

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: prefixpath_route
6         uri: https://example.org
7         filters:
8         - prefixpath=/mypath

3.1.6.  requestratelimiter gatewayfilter factory

requestratelimiter gatewayfilter 用一个ratelimiter实现来决定当前请求是否被允许处理。如果不被允许,默认将返回一个http 429状态,表示太多的请求。 

这个过滤器采用一个可选的keyresolver参数。keyresolver是实现了keyresolver接口的一个bean。在配置中,通过spel表达式引用它。例如,#{@mykeyresolver}是一个spel表达式,它是对名字叫mykeyresolver的bean的引用。keyresolver默认的实现是principalnamekeyresolver。

默认情况下,如果keyresolver没有找到一个key,那么请求将会被拒绝。你可以调整这种行为,通过设置spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key (true or false) 和 spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code属性。

redis基于 token bucket algorithm (令牌桶算法)实现了一个requestratelimiter

redis-rate-limiter.replenishrate 属性指定一个用户每秒允许多少个请求,而没有任何丢弃的请求。这是令牌桶被填充的速率。

redis-rate-limiter.burstcapacity 属性指定用户在一秒钟内执行的最大请求数。这是令牌桶可以容纳的令牌数。将此值设置为零将阻止所有请求。

redis-rate-limiter.requestedtokens 属性指定一个请求要花费多少个令牌。这是每个请求从存储桶中获取的令牌数,默认为1。

通过将replenishrate和burstcapacity设置成相同的值可以实现稳定的速率。通过将burstcapacity设置为高于replenishrate,可以允许临时突发。 在这种情况下,速率限制器需要在两次突发之间保留一段时间(根据replenishrate),因为两个连续的突发将导致请求丢弃(http 429-太多请求)。 

通过将replenishrate设置为所需的请求数,将requesttokens设置为以秒为单位的时间跨度并将burstcapacity设置为replenishrate和requestedtoken的乘积。可以达到1个请求的速率限制。 例如:设置replenishrate = 1,requestedtokens = 60和burstcapacity = 60将导致限制为每分钟1个请求。

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5       - id: requestratelimiter_route
 6         uri: https://example.org
 7         filters:
 8         - name: requestratelimiter
 9           args:
10             redis-rate-limiter.replenishrate: 10
11             redis-rate-limiter.burstcapacity: 20
12             redis-rate-limiter.requestedtokens: 1 

keyresolver

1 @bean
2 keyresolver userkeyresolver() {
3     return exchange -> mono.just(exchange.getrequest().getqueryparams().getfirst("user"));
4 }

上面的例子,定义了每个用户每秒运行10个请求,令牌桶的容量是20,那么,下一秒将只剩下10个令牌可用。keyresolver实现仅仅只是简单取请求参数中的user,当然在生产环境中不推荐这么做。

说白了,keyresolver就是决定哪些请求属于同一个用户的。比如,header中userid相同的就认为是同一个用户的请求。

当然,你也可以自己实现一个ratelimiter,在配置的时候用spel表达式#{@myratelimiter}去引用它。例如:

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5       - id: requestratelimiter_route
 6         uri: https://example.org
 7         filters:
 8         - name: requestratelimiter
 9           args:
10             rate-limiter: "#{@myratelimiter}"
11             key-resolver: "#{@userkeyresolver}"

补充:(token bucket)令牌桶

https://en.wikipedia.org/wiki/token_bucket

令牌桶是在分组交换计算机网络和电信网络中使用的算法。它可以用来检查数据包形式的数据传输是否符合定义的带宽和突发性限制(对流量不均匀性或变化的度量)。

令牌桶算法就好比是一个的固定容量桶,通常以固定速率向其中添加令牌。一个令牌通常代表一个字节。当要检查数据包是否符合定义的限制时,将检查令牌桶以查看其当时是否包含足够的令牌。如果有足够数量的令牌,并假设令牌以字节为单位,那么,与数据包字节数量等效数量的令牌将被删除,并且该数据包可以通过继续传输。如果令牌桶中的令牌数量不够,则数据包不符合要求,并且令牌桶的令牌数量不会变化。不合格的数据包可以有多种处理方式:

  • 它们可能会被丢弃
  • 当桶中积累了足够的令牌时,可以将它们加入队列进行后续传输
  • 它们可以被传输,但被标记为不符合,如果网络负载过高,可能随后被丢弃

(ps:这句话的意思是说,想象有一个桶,以固定速率向桶中添加令牌。假设一个令牌等效于一个字节,当一个数据包到达时,假设这个数据包的大小是n字节,如果桶中有足够多的令牌,即桶中令牌的数量大于n,则该数据可以通过,并且桶中要删除n个令牌。如果桶中令牌数不够,则根据情况该数据包可能直接被丢弃,也可能一直等待直到令牌足够,也可能继续传输,但被标记为不合格。还是不够通俗,这样,如果把令牌桶想象成一个水桶的话,令牌想象成水滴的话,那么这个过程就变成了以恒定速率向水桶中滴水,当有人想打一碗水时,如果这个人的碗很小,只能装30滴水,而水桶中水滴数量超过30,那么这个人就可以打一碗水,然后就走了,相应的,水桶中的水在这个人打完以后自然就少了30滴。过了一会儿,又有一个人来打水,他拿的碗比较大,一次能装100滴水,这时候桶里的水不够,这个时候他可能就走了,或者在这儿等着,等到桶中积累了100滴的时候再打。哈哈哈,就是酱紫,不知道大家见过水车没有……)

令牌桶算法可以简单地这样理解:

  • 每 1/r 秒有一个令牌被添加到令牌桶
  • 令牌桶最多可以容纳 b 个令牌。当一个令牌到达时,令牌桶已经满了,那么它将会被丢弃。
  • 当一个 n 字节大小的数据包到达时:
    • 如果令牌桶中至少有n个令牌,则从令牌桶中删除n个令牌,并将数据包发送到网络。
    • 如果可用的令牌少于n个,则不会从令牌桶中删除任何令牌,并且将数据包视为不合格。 

3.1.7. redirectto gatewayfilter factory 

redirectto gatewayfilter 有两个参数:status 和 url。status应该是300系列的。不解释,看示例:

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: prefixpath_route
6         uri: https://example.org
7         filters:
8         - redirectto=302, https://acme.org

3.1.8.  removerequestheader gatewayfilter factory 

1 spring:
2   cloud:
3     gateway:
4       routes:
5       - id: removerequestheader_route
6         uri: https://example.org
7         filters:
8         - removerequestheader=x-request-foo

3.1.9.  rewritepath gatewayfilter factory 

 1 spring:
 2   cloud:
 3     gateway:
 4       routes:
 5       - id: rewritepath_route
 6         uri: https://example.org
 7         predicates:
 8         - path=/foo/**
 9         filters:
10         - rewritepath=/red(?<segment>/?.*), $\{segment}

3.1.10.  default filters 

为了添加一个过滤器,并将其应用到所有路由上,你可以使用spring.cloud.gateway.default-filters,这个属性值是一个过滤器列表

1 spring:
2   cloud:
3     gateway:
4       default-filters:
5       - addresponseheader=x-response-default-red, default-blue
6       - prefixpath=/httpbin

3.2. global filters

globalfilter应用于所有路由

3.2.1.  globalfilter与gatewayfilter组合的顺序 

当一个请求请求与匹配某个路由时,过滤web处理程序会将globalfilter的所有实例和gatewayfilter的所有特定于路由的实例添加到过滤器链中。该组合的过滤器链由org.springframework.core.ordered接口排序,可以通过实现getorder()方法进行设置。

由于spring cloud gateway区分过滤器逻辑执行的“pre”和“post”阶段,因此,优先级最高的过滤器在“pre”阶段是第一个,在“post”阶段是最后一个。

 1 @bean
 2 public globalfilter customfilter() {
 3     return new customglobalfilter();
 4 }
 5 
 6 public class customglobalfilter implements globalfilter, ordered {
 7 
 8     @override
 9     public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
10         log.info("custom global filter");
11         return chain.filter(exchange);
12     }
13 
14     @override
15     public int getorder() {
16         return -1;
17     }
18 }

补充:(token bucket)令牌桶

https://en.wikipedia.org/wiki/token_bucket

令牌桶是在分组交换计算机网络和电信网络中使用的算法。它可以用来检查数据包形式的数据传输是否符合定义的带宽和突发性限制(对流量不均匀性或变化的度量)。

令牌桶算法就好比是一个的固定容量桶,通常以固定速率向其中添加令牌。一个令牌通常代表一个字节。当要检查数据包是否符合定义的限制时,将检查令牌桶以查看其当时是否包含足够的令牌。如果有足够数量的令牌,并假设令牌以字节为单位,那么,与数据包字节数量等效数量的令牌将被删除,并且该数据包可以通过继续传输。如果令牌桶中的令牌数量不够,则数据包不符合要求,并且令牌桶的令牌数量不会变化。不合格的数据包可以有多种处理方式:

  • 它们可能会被丢弃
  • 当桶中积累了足够的令牌时,可以将它们加入队列进行后续传输
  • 它们可以被传输,但被标记为不符合,如果网络负载过高,可能随后被丢弃

(ps:这句话的意思是说,想象有一个桶,以固定速率向桶中添加令牌。假设一个令牌等效于一个字节,当一个数据包到达时,假设这个数据包的大小是n字节,如果桶中有足够多的令牌,即桶中令牌的数量大于n,则该数据可以通过,并且桶中要删除n个令牌。如果桶中令牌数不够,则根据情况该数据包可能直接被丢弃,也可能一直等待直到令牌足够,也可能继续传输,但被标记为不合格。还是不够通俗,这样,如果把令牌桶想象成一个水桶的话,令牌想象成水滴的话,那么这个过程就变成了以恒定速率向水桶中滴水,当有人想打一碗水时,如果这个人的碗很小,只能装30滴水,而水桶中水滴数量超过30,那么这个人就可以打一碗水,然后就走了,相应的,水桶中的水在这个人打完以后自然就少了30滴。过了一会儿,又有一个人来打水,他拿的碗比较大,一次能装100滴水,这时候桶里的水不够,这个时候他可能就走了,或者在这儿等着,等到桶中积累了100滴的时候再打。哈哈哈,就是酱紫,不知道大家见过水车没有……)

令牌桶算法可以简单地这样理解:

  • 每 1/r 秒有一个令牌被添加到令牌桶
  • 令牌桶最多可以容纳 b 个令牌。当一个令牌到达时,令牌桶已经满了,那么它将会被丢弃。
  • 当一个 n 字节大小的数据包到达时:
    • 如果令牌桶中至少有n个令牌,则从令牌桶中删除n个令牌,并将数据包发送到网络。
    • 如果可用的令牌少于n个,则不会从令牌桶中删除任何令牌,并且将数据包视为不合格。 

4. docs

https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.release/reference/html/#gatewayfilter-factories

https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.release/reference/html/#gateway-request-predicates-factories 

 

https://en.wikipedia.org/wiki/token_bucket