-
Notifications
You must be signed in to change notification settings - Fork 7
/
gRPC.go
81 lines (71 loc) · 1.59 KB
/
gRPC.go
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
package bearerware
import (
"fmt"
"strings"
"github.com/dgrijalva/jwt-go"
"golang.org/x/net/context"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)
type jwtAccess struct {
jsonKey string
}
/*
NewJWTAccessFromJWT creates a JWT credentials.PerRPCCredentials for use in gRPC
requests.
*/
func NewJWTAccessFromJWT(
jsonKey string,
) (credentials.PerRPCCredentials, error) {
return jwtAccess{jsonKey}, nil
}
func (j jwtAccess) GetRequestMetadata(
ctx context.Context,
uri ...string,
) (map[string]string, error) {
return map[string]string{
authHeader: fmt.Sprintf("%s%s", strings.Title(bearer), j.jsonKey),
}, nil
}
func (j jwtAccess) RequireTransportSecurity() bool {
return true
}
/*
JWTFromContext **deprecated** use `JWTFromIncomingContext`
*/
func JWTFromContext(
ctx context.Context,
keyFunc jwt.Keyfunc,
signingMethod jwt.SigningMethod,
) (*jwt.Token, error) {
return JWTFromIncomingContext(ctx, keyFunc, signingMethod)
}
/*
JWTFromIncomingContext extracts a valid JWT from a context.Contexts or returns
and error
*/
func JWTFromIncomingContext(
ctx context.Context,
keyFunc jwt.Keyfunc,
signingMethod jwt.SigningMethod,
) (*jwt.Token, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errRestricted
}
var tokenStrings []string
for k := range md {
if authHeader == k {
tokenStrings = md[k]
break
}
}
if len(tokenStrings) == 0 {
return nil, errRestricted
}
tokenString, ok := tokenFromBearer(tokenStrings[0])
if !ok {
return nil, errBearerFormat
}
return validJWTFromString(tokenString, keyFunc, signingMethod)
}