Blame view

utils/jwt.go 2.33 KB
ee23102d   zhangqijia   支持mongo, grpc接服务器
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  package utils
  
  import (
  	"context"
  	"fmt"
  	"pro2d/protos/pb"
  	"time"
  
  	jwt "github.com/dgrijalva/jwt-go"
  	"google.golang.org/grpc/metadata"
  )
  
  func CreateToken(account *pb.AccountInfo) (tokenString string) {
  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  		"iss":      "pro2d-app-server",
  		"aud":      "pro2d-app-server",
  		"nbf":      time.Now().Unix(),
  		"exp":      time.Now().Add(time.Hour).Unix(),
  		"sub":      "pro2d",
  		"phone": account.Phone,
  		"uid": account.Uid,
  		"device": account.Device,
  	})
  	tokenString, err := token.SignedString([]byte(Pro2DTokenSignedString))
  	if err != nil {
  		panic(err)
  	}
  	return tokenString
  }
  
  func ParseToken(tokenStr string)*pb.AccountInfo  {
  	var clientClaims Claims
  	token, err := jwt.ParseWithClaims(tokenStr, &clientClaims, func(token *jwt.Token) (interface{}, error) {
  		if token.Header["alg"] != "HS256" {
  			//panic("ErrInvalidAlgorithm")
  			Sugar.Error("ErrInvalidAlgorithm")
  			return nil, nil
  		}
  		return []byte(Pro2DTokenSignedString), nil
  	})
  	if err != nil {
  		Sugar.Error("jwt parse error")
  		return nil
  	}
  
  	if !token.Valid {
  		Sugar.Error("ErrInvalidToken")
  		return nil
  	}
  	return &clientClaims.AccountInfo
  }
  
  // AuthToken 自定义认证
  type AuthToken struct {
  	Token string
  }
  
  func (c AuthToken) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
  	return map[string]string{
  		"authorization": c.Token,
  	}, nil
  }
  
  func (c AuthToken) RequireTransportSecurity() bool {
  	return false
  }
  
  // Claims defines the struct containing the token claims.
  type Claims struct {
  	jwt.StandardClaims
  	//phone string 	`json:"phone"`
  	//uid int64 		`json:"uid"`
  	//device string 	`json:"device"`
  	pb.AccountInfo
  }
  
  // 从 context 的 metadata 中,取出 token
  func getTokenFromContext(ctx context.Context) (string, error) {
  	md, ok := metadata.FromIncomingContext(ctx)
  	if !ok {
  		return "", fmt.Errorf("ErrNoMetadataInContext")
  	}
  	// md 的类型是 type MD map[string][]string
  	token, ok := md["authorization"]
  	if !ok || len(token) == 0 {
  		return "", fmt.Errorf("ErrNoAuthorizationInMetadata")
  	}
  	// 因此,token 是一个字符串数组,我们只用了 token[0]
  	return token[0], nil
  }
  
  func CheckAuth(ctx context.Context) *pb.AccountInfo {
  	tokenStr, err := getTokenFromContext(ctx)
  	if err != nil {
  		panic("get token from context error")
  	}
  	return ParseToken(tokenStr)
  }