-
Notifications
You must be signed in to change notification settings - Fork 0
/
intercepter.go
51 lines (42 loc) · 1.3 KB
/
intercepter.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
package intercepter
import (
"context"
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
const (
isserService = "service.eventmanager.live"
expTime = time.Second * 5
secretService = "super_secure"
)
func WithUnary(f grpc.UnaryClientInterceptor) grpc.DialOption {
return grpc.WithUnaryInterceptor(f)
}
// WithAuth serves as an grpc client intercepter appending the grpc context with the
// JWT user token for authentication on service level
func WithServiceAuth(ctx context.Context, method string, req interface{}, reply interface{},
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption,
) error {
accessToken, err := generateServiceToken()
if err != nil {
return err
}
meta := metadata.Pairs("datalab-service-token", accessToken)
newCtx := metadata.NewOutgoingContext(ctx, meta)
return invoker(newCtx, method, req, reply, cc, opts...)
}
func generateServiceToken() (string, error) {
claims := jwt.MapClaims{
"iat": isserService,
"exp": time.Now().Add(expTime).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
accessToken, err := token.SignedString([]byte(secretService))
if err != nil {
return "", fmt.Errorf("[jwts.IssueUser] could not sign token: %v", err)
}
return accessToken, nil
}