-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtoken.go
89 lines (71 loc) · 2.47 KB
/
token.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
82
83
84
85
86
87
88
89
package token
import (
"context"
"fmt"
"path"
"github.com/alexfalkowski/go-service/security/header"
"github.com/alexfalkowski/go-service/security/token"
"github.com/alexfalkowski/go-service/transport/meta"
"github.com/alexfalkowski/go-service/transport/strings"
middleware "github.com/grpc-ecosystem/go-grpc-middleware/v2"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
)
// VerifyToken from context.
func VerifyToken(ctx context.Context, verifier token.Verifier) (context.Context, error) {
token := meta.Authorization(ctx).Value()
return verifier.Verify(ctx, []byte(token))
}
// UnaryServerInterceptor for token.
func UnaryServerInterceptor(verifier token.Verifier) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
service := path.Dir(info.FullMethod)[1:]
if strings.IsHealth(service) {
return handler(ctx, req)
}
ctx, err := VerifyToken(ctx, verifier)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "verify token: %s", err.Error())
}
return handler(ctx, req)
}
}
// StreamServerInterceptor for token.
func StreamServerInterceptor(verifier token.Verifier) grpc.StreamServerInterceptor {
return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
service := path.Dir(info.FullMethod)[1:]
if strings.IsHealth(service) {
return handler(srv, stream)
}
ctx := stream.Context()
ctx, err := VerifyToken(ctx, verifier)
if err != nil {
return status.Errorf(codes.Unauthenticated, "verify token: %s", err.Error())
}
wrapped := middleware.WrapServerStream(stream)
wrapped.WrappedContext = ctx
return handler(srv, wrapped)
}
}
// NewPerRPCCredentials for token.
func NewPerRPCCredentials(generator token.Generator) credentials.PerRPCCredentials {
return &tokenPerRPCCredentials{generator: generator}
}
type tokenPerRPCCredentials struct {
generator token.Generator
}
func (p *tokenPerRPCCredentials) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) {
_, t, err := p.generator.Generate(ctx)
if err != nil {
return nil, err
}
if len(t) == 0 {
return nil, header.ErrInvalidAuthorization
}
return map[string]string{"authorization": fmt.Sprintf("%s %s", header.BearerAuthorization, t)}, nil
}
func (p *tokenPerRPCCredentials) RequireTransportSecurity() bool {
return false
}