grpc.go42 lines, 1.4 KB
| 1 | package authn |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | |
| 9 | "google.golang.org/grpc" |
| 10 | "google.golang.org/grpc/metadata" |
| 11 | ) |
| 12 | |
| 13 | // UnaryInterceptor is Require, for gRPC. It only lets RPCs with a valid access |
| 14 | // token through, sent as authorization: Bearer <token> in the metadata. RPCs |
| 15 | // to the services named in public, like health checks, need no token. |
| 16 | func (v *Verifier) UnaryInterceptor(public ...string) grpc.UnaryServerInterceptor { |
| 17 | return func( |
| 18 | ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, |
| 19 | ) (any, error) { |
| 20 | // FullMethod looks like /wallet.v1.WalletService/GetBalance. |
| 21 | service, _, _ := strings.Cut(strings.TrimPrefix(info.FullMethod, "/"), "/") |
| 22 | if slices.Contains(public, service) { |
| 23 | return handler(ctx, req) |
| 24 | } |
| 25 | values := metadata.ValueFromIncomingContext(ctx, "authorization") |
| 26 | if len(values) != 1 || bearer(values[0]) == "" { |
| 27 | return nil, ErrMissingToken |
| 28 | } |
| 29 | user, err := v.Verify(bearer(values[0])) |
| 30 | if err != nil { |
| 31 | slog.InfoContext(ctx, "access token refused", "err", err) |
| 32 | return nil, ErrInvalidToken |
| 33 | } |
| 34 | return handler(withUser(ctx, user), req) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // WithToken returns a copy of ctx that sends token with every gRPC call made |
| 39 | // with it: the client's half of UnaryInterceptor. |
| 40 | func WithToken(ctx context.Context, token string) context.Context { |
| 41 | return metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+token) |
| 42 | } |