激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術(shù)及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 詳解用JWT對SpringCloud進行認證和鑒權(quán)

詳解用JWT對SpringCloud進行認證和鑒權(quán)

2021-07-22 16:23慕容千語 Java教程

這篇文章主要介紹了詳解用JWT對SpringCloud進行認證和鑒權(quán),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

jwt(json web token)是基于rfc 7519標準定義的一種可以安全傳輸?shù)男∏珊妥园膉son對象。由于數(shù)據(jù)是使用數(shù)字簽名的,所以是可信任的和安全的。jwt可以使用hmac算法對secret進行加密或者使用rsa的公鑰私鑰對來進行簽名。

jwt通常由頭部(header),負載(payload),簽名(signature)三個部分組成,中間以.號分隔,其格式為header.payload.signature

header:聲明令牌的類型和使用的算法

  • alg:簽名的算法
  • typ:token的類型,比如jwt

payload:也稱為jwt claims,包含用戶的一些信息

系統(tǒng)保留的聲明(reserved claims):

  • iss (issuer):簽發(fā)人
  • exp (expiration time):過期時間
  • sub (subject):主題
  • aud (audience):受眾用戶
  • nbf (not before):在此之前不可用
  • iat (issued at):簽發(fā)時間
  •  jti (jwt id):jwt唯一標識,能用于防止jwt重復使用

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

私有的聲明(private claims):根據(jù)業(yè)務需要自己定義的數(shù)據(jù)

signature:簽名

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

jwt的特點:

  • jwt默認是不加密的,不能把用戶敏感類信息放在payload部分。
  • jwt 不僅可以用于認證,也可以用于交換信息。
  • jwt的最大缺點是服務器不保存會話狀態(tài),所以在使用期間不可能取消令牌或更改令牌的權(quán)限。
  • jwt本身包含認證信息,為了減少盜用,jwt的有效期不宜設置太長。
  • 為了減少盜用和竊取,jwt不建議使用http協(xié)議來傳輸代碼,而是使用加密的https協(xié)議進行傳輸。
  • 首次生成token比較慢,比較耗cpu,在高并發(fā)的情況下需要考慮cpu占用問題。
  • 生成的token比較長,可能需要考慮流量問題。

認證原理:

  • 客戶端向服務器申請授權(quán),服務器認證以后,生成一個token字符串并返回給客戶端,此后客戶端在請求
  • 受保護的資源時攜帶這個token,服務端進行驗證再從這個token中解析出用戶的身份信息。

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

authorization: <token>

 需要將服務器設置為接受來自所有域的請求,用access-control-allow-origin: *

  另一種做法是,跨域的時候,jwt就放在post請求的數(shù)據(jù)體里面。

對jwt實現(xiàn)token續(xù)簽的做法:

1、額外生成一個refreshtoken用于獲取新token,refreshtoken需存儲于服務端,其過期時間比jwt的過期時間要稍長。

2、用戶攜帶refreshtoken參數(shù)請求token刷新接口,服務端在判斷refreshtoken未過期后,取出關(guān)聯(lián)的用戶信息和當前token。

3、使用當前用戶信息重新生成token,并將舊的token置于黑名單中,返回新的token。

創(chuàng)建用于登錄認證的工程auth-service:

1、 創(chuàng)建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"; //簽發(fā)人
 
  /**
   * 生成簽名
   */
  public static string generatetoken(string username){
    date now = new date();
    algorithm algorithm = algorithm.hmac256(secret_key); //算法
     
    string token = jwt.create()
      .withissuer(issuer) //簽發(fā)人
      .withissuedat(now) //簽發(fā)時間
      .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();
       
      //數(shù)據(jù)放入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、創(chuàng)建全局過濾器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、關(guān)鍵的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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 奇米888一区二区三区 | 激情综合在线 | 成人免费一区二区三区在线观看 | 国产乱淫av片免费 | 黄污视频在线看 | 视频一区国产 | 狠狠操人人干 | 97人操| 成人午夜免费看 | 操操电影| 亚洲 综合 欧美 动漫 丝袜图 | 免费看污视频在线观看 | 俄罗斯hdxxx 日夜操天天干 | 国产88久久久国产精品免费二区 | 日本中文字幕电影在线观看 | 成人免费看毛片 | 亚洲国产精品99 | 国产成人精品免高潮在线观看 | 一级做受毛片免费大片 | 麻豆视频观看 | 免费看欧美一级特黄a毛片 九色com | 久久一区二区三区av | 婷婷亚洲一区二区三区 | 久草免费资源视频 | 护士hd老师fre0性xxx | 久久精品国产久精国产 | 久久99久久98精品免观看软件 | 极品五月天 | 斗破苍穹在线免费 | 免费一级在线 | 999插插插| 国产一级一国产一级毛片 | 91丝袜 | caoporn国产一区二区 | 成人免费网站在线观看 | 午夜在线视频一区二区三区 | 久久久久中精品中文字幕19 | 亚洲福利在线视频 | 黄色一级片免费观看 | 美女视频大全网站免费 | 欧美成人免费一区二区三区 |