详解用JWT对SpringCloud进行认证和鉴权

2025-05-29 0 18

jwt(json web token)是基于rfc 7519标准定义的一种可以安全传输的小巧和自包含的json对象。由于数据是使用数字签名的,所以是可信任的和安全的。jwt可以使用hmac算法对secret进行加密或者使用rsa的公钥私钥对来进行签名。

jwt通常由头部(header),负载(payload),签名(signature)三个部分组成,中间以.号分隔,其格式为header.payload.signature

header:声明令牌的类型和使用的算法

  • alg:签名的算法
  • typ:token的类型,比如jwt

payload:也称为jwt claims,包含用户的一些信息

系统保留的声明(reserved claims):

  • iss (issuer):签发人
  • exp (expiration time):过期时间
  • sub (subject):主题
  • aud (audience):受众用户
  • nbf (not before):在此之前不可用
  • iat (issued at):签发时间
  • jti (jwt id):jwt唯一标识,能用于防止jwt重复使用

公共的声明(public):见http://www.iana.org/assignments/jwt/jwt.xhtml

私有的声明(private claims):根据业务需要自己定义的数据

signature:签名

签名格式:hmacsha256(base64urlencode(header) + "." + base64urlencode(payload), secret)

jwt的特点:

  • jwt默认是不加密的,不能把用户敏感类信息放在payload部分。
  • jwt 不仅可以用于认证,也可以用于交换信息。
  • jwt的最大缺点是服务器不保存会话状态,所以在使用期间不可能取消令牌或更改令牌的权限。
  • jwt本身包含认证信息,为了减少盗用,jwt的有效期不宜设置太长。
  • 为了减少盗用和窃取,jwt不建议使用http协议来传输代码,而是使用加密的https协议进行传输。
  • 首次生成token比较慢,比较耗cpu,在高并发的情况下需要考虑cpu占用问题。
  • 生成的token比较长,可能需要考虑流量问题。

认证原理:

  • 客户端向服务器申请授权,服务器认证以后,生成一个token字符串并返回给客户端,此后客户端在请求
  • 受保护的资源时携带这个token,服务端进行验证再从这个token中解析出用户的身份信息。

jwt的使用方式:一种做法是放在http请求的头信息authorization字段里面,格式如下:

authorization: <token>

需要将服务器设置为接受来自所有域的请求,用access-control-allow-origin: *

另一种做法是,跨域的时候,jwt就放在post请求的数据体里面。

对jwt实现token续签的做法:

1、额外生成一个refreshtoken用于获取新token,refreshtoken需存储于服务端,其过期时间比jwt的过期时间要稍长。

2、用户携带refreshtoken参数请求token刷新接口,服务端在判断refreshtoken未过期后,取出关联的用户信息和当前token。

3、使用当前用户信息重新生成token,并将旧的token置于黑名单中,返回新的token。

创建用于登录认证的工程auth-service:

1、 创建pom.xml文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67
<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/maven-v4_0_0.xsd">

<modelversion>4.0.0</modelversion>

<groupid>com.seasy.springcloud</groupid>

<artifactid>auth-service</artifactid>

<version>1.0.0</version>

<packaging>jar</packaging>

<parent>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-parent</artifactid>

<version>2.0.8.release</version>

<relativepath/>

</parent>

<properties>

<java.version>1.8</java.version>

<project.build.sourceencoding>utf-8</project.build.sourceencoding>

<project.reporting.outputencoding>utf-8</project.reporting.outputencoding>

</properties>

<dependencies>

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-web</artifactid>

</dependency>

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-actuator</artifactid>

</dependency>

<!-- spring cloud -->

<dependency>

<groupid>org.springframework.cloud</groupid>

<artifactid>spring-cloud-starter-netflix-eureka-client</artifactid>

</dependency>

<!-- redis -->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-data-redis</artifactid>

</dependency>

<dependency>

<groupid>org.apache.commons</groupid>

<artifactid>commons-pool2</artifactid>

</dependency>

<!-- jwt -->

<dependency>

<groupid>com.auth0</groupid>

<artifactid>java-jwt</artifactid>

<version>3.7.0</version>

</dependency>

</dependencies>

<dependencymanagement>

<dependencies>

<dependency>

<groupid>org.springframework.cloud</groupid>

<artifactid>spring-cloud-dependencies</artifactid>

<version>finchley.release</version>

<type>pom</type>

<scope>import</scope>

</dependency>

</dependencies>

</dependencymanagement>

</project>

2、jwt工具类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51
public class jwtutil {

public static final string secret_key = "123456"; //秘钥

public static final long token_expire_time = 5 * 60 * 1000; //token过期时间

public static final long refresh_token_expire_time = 10 * 60 * 1000; //refreshtoken过期时间

private static final string issuer = "issuer"; //签发人

/**

* 生成签名

*/

public static string generatetoken(string username){

date now = new date();

algorithm algorithm = algorithm.hmac256(secret_key); //算法

string token = jwt.create()

.withissuer(issuer) //签发人

.withissuedat(now) //签发时间

.withexpiresat(new date(now.gettime() + token_expire_time)) //过期时间

.withclaim("username", username) //保存身份标识

.sign(algorithm);

return token;

}

/**

* 验证token

*/

public static boolean verify(string token){

try {

algorithm algorithm = algorithm.hmac256(secret_key); //算法

jwtverifier verifier = jwt.require(algorithm)

.withissuer(issuer)

.build();

verifier.verify(token);

return true;

} catch (exception ex){

ex.printstacktrace();

}

return false;

}

/**

* 从token获取username

*/

public static string getusername(string token){

try{

return jwt.decode(token).getclaim("username").asstring();

}catch(exception ex){

ex.printstacktrace();

}

return "";

}

}

3、logincontroller类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53
@restcontroller

public class logincontroller {

@autowired

stringredistemplate redistemplate;

/**

* 登录认证

* @param username 用户名

* @param password 密码

*/

@getmapping("/login")

public authresult login(@requestparam string username, @requestparam string password) {

if("admin".equals(username) && "admin".equals(password)){

//生成token

string token = jwtutil.generatetoken(username);

//生成refreshtoken

string refreshtoken = stringutil.getuuidstring();

//数据放入redis

redistemplate.opsforhash().put(refreshtoken, "token", token);

redistemplate.opsforhash().put(refreshtoken, "username", username);

//设置token的过期时间

redistemplate.expire(refreshtoken, jwtutil.refresh_token_expire_time, timeunit.milliseconds);

return new authresult(0, "success", token, refreshtoken);

}else{

return new authresult(1001, "username or password error");

}

}

/**

* 刷新token

*/

@getmapping("/refreshtoken")

public authresult refreshtoken(@requestparam string refreshtoken) {

string username = (string)redistemplate.opsforhash().get(refreshtoken, "username");

if(stringutil.isempty(username)){

return new authresult(1003, "refreshtoken error");

}

//生成新的token

string newtoken = jwtutil.generatetoken(username);

redistemplate.opsforhash().put(refreshtoken, "token", newtoken);

return new authresult(0, "success", newtoken, refreshtoken);

}

@getmapping("/")

public string index() {

return "auth-service: " + localdatetime.now().format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss"));

}

}

4、application配置信息

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
spring.application.name=auth-service

server.port=4040

eureka.instance.hostname=${spring.cloud.client.ip-address}

eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}

eureka.instance.prefer-ip-address=true

eureka.client.service-url.defaultzone=http://root:123456@${eureka.instance.hostname}:7001/eureka/

#redis

spring.redis.database=0

spring.redis.timeout=3000ms

spring.redis.lettuce.pool.max-active=100

spring.redis.lettuce.pool.max-wait=-1ms

spring.redis.lettuce.pool.min-idle=0

spring.redis.lettuce.pool.max-idle=8

#standalone

spring.redis.host=192.168.134.134

spring.redis.port=7001

#sentinel

#spring.redis.sentinel.master=mymaster

#spring.redis.sentinel.nodes=192.168.134.134:26379,192.168.134.134:26380

5、启动类

?

1

2

3

4

5

6

7
@springbootapplication

@enableeurekaclient

public class main{

public static void main(string[] args){

springapplication.run(main.class, args);

}

}

改造springcloud gateway工程

1、在pom.xml文件添加依赖

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
<!-- redis -->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-data-redis</artifactid>

</dependency>

<dependency>

<groupid>org.apache.commons</groupid>

<artifactid>commons-pool2</artifactid>

</dependency>

<!-- jwt -->

<dependency>

<groupid>com.auth0</groupid>

<artifactid>java-jwt</artifactid>

<version>3.7.0</version>

</dependency>

2、创建全局过滤器jwtauthfilter

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47
@component

public class jwtauthfilter implements globalfilter, ordered{

@override

public int getorder() {

return -100;

}

@override

public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {

string url = exchange.getrequest().geturi().getpath();

//忽略以下url请求

if(url.indexof("/auth-service/") >= 0){

return chain.filter(exchange);

}

//从请求头中取得token

string token = exchange.getrequest().getheaders().getfirst("authorization");

if(stringutil.isempty(token)){

serverhttpresponse response = exchange.getresponse();

response.setstatuscode(httpstatus.ok);

response.getheaders().add("content-type", "application/json;charset=utf-8");

response res = new response(401, "401 unauthorized");

byte[] responsebyte = jsonobject.fromobject(res).tostring().getbytes(standardcharsets.utf_8);

databuffer buffer = response.bufferfactory().wrap(responsebyte);

return response.writewith(flux.just(buffer));

}

//请求中的token是否在redis中存在

boolean verifyresult = jwtutil.verify(token);

if(!verifyresult){

serverhttpresponse response = exchange.getresponse();

response.setstatuscode(httpstatus.ok);

response.getheaders().add("content-type", "application/json;charset=utf-8");

response res = new response(1004, "invalid token");

byte[] responsebyte = jsonobject.fromobject(res).tostring().getbytes(standardcharsets.utf_8);

databuffer buffer = response.bufferfactory().wrap(responsebyte);

return response.writewith(flux.just(buffer));

}

return chain.filter(exchange);

}

}

3、关键的application配置信息

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
spring:

application:

name: service-gateway

cloud:

gateway:

discovery:

locator:

enabled: true

lowercaseserviceid: true

routes:

#认证服务路由

- id: auth-service

predicates:

- path=/auth-service/**

uri: lb://auth-service

filters:

- stripprefix=1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.jianshu.com/p/cf9ad8c3621d

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解用JWT对SpringCloud进行认证和鉴权 https://www.kuaiidc.com/109772.html

相关文章

发表评论
暂无评论