Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Interceptors and Security

Token Authentication and Authorization in gRPC

Authenticate gRPC calls with bearer tokens and API keys: per-RPC credentials on the client, auth interceptors on the server, and role checks, with runnable HMAC token examples in Go.

TLS protects the connection. It does not tell you which user is behind a single call, especially when many users share one connection through a gateway or a mobile app. For that you attach a credential to each call, usually a token in the authorization metadata entry, and verify it on the server.

Two ideas keep this clean. Authentication answers "who are you?" and fails with UNAUTHENTICATED. Authorization answers "may you do this?" and fails with PERMISSION_DENIED. Mixing them up confuses clients, as explained in status codes.

The grpc-go library itself cannot run here, so its API is shown read-only. The token creation and checking code (HMAC signatures, expiry, roles) is real Go and runs on the site.

The flow

sequenceDiagram
    participant U as Client
    participant A as Auth service
    participant S as gRPC service
    U->>A: Login(user, password)
    A-->>U: signed token (expires in 15 min)
    U->>S: GetOrder + metadata authorization: Bearer token
    Note over S: auth interceptor:<br/>check signature, expiry, scope
    S-->>U: Order, or UNAUTHENTICATED / PERMISSION_DENIED

The client logs in once, then sends the token with every call.

Sending a token: per-RPC credentials (real API)

grpc-go has a small interface, credentials.PerRPCCredentials, for exactly this. The library calls it before each RPC and adds the returned metadata:

Go
type tokenAuth struct {
    token string
}

func (t tokenAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
    return map[string]string{"authorization": "Bearer " + t.token}, nil
}

// The token is only sent over a secure channel:
func (t tokenAuth) RequireTransportSecurity() bool { return true }

conn, err := grpc.NewClient(target,
    grpc.WithTransportCredentials(creds),
    grpc.WithPerRPCCredentials(tokenAuth{token: tok}),
)

RequireTransportSecurity returning true makes grpc-go refuse to send the token over a plaintext connection, which protects you from leaking it by accident. For tokens that expire, GetRequestMetadata is the place to refresh: it runs per call, so it can return a fresh token. The golang.org/x/oauth2 package provides ready-made oauth.TokenSource credentials for OAuth 2.0.

Checking a token: an auth interceptor (real API)

Go
func authInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
    if publicMethods[info.FullMethod] {
        return h(ctx, req)
    }
    md, _ := metadata.FromIncomingContext(ctx)
    values := md.Get("authorization")
    if len(values) == 0 {
        return nil, status.Error(codes.Unauthenticated, "missing authorization header")
    }
    token := strings.TrimPrefix(values[0], "Bearer ")
    claims, err := verify(token)
    if err != nil {
        return nil, status.Error(codes.Unauthenticated, "invalid or expired token")
    }
    ctx = context.WithValue(ctx, claimsKey{}, claims)
    return h(ctx, req)
}

Keep a list of public methods (login, health checks) that skip the check. The interceptor puts the verified claims into the context, so handlers can read the user without re-parsing the token.

What a token contains

A common choice is a JWT (JSON Web Token): three base64url parts separated by dots, header.payload.signature. The payload holds claims such as sub (the user), exp (expiry time) and scope/roles. The signature, an HMAC with a shared secret or an RSA/ECDSA signature, lets the server detect tampering. Because the payload is only encoded, not encrypted, never put secrets in it.

In production use a well-tested library for JWTs (for example golang-jwt), which also handles algorithm confusion attacks. To show the mechanics without a dependency, this program builds and checks a minimal HS256-signed token with the standard library:

Go Sign and verify an HMAC token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The forged token keeps the old signature but changes the payload, so the signature no longer matches. hmac.Equal compares in constant time, which avoids leaking information through timing.

Authorization: roles per method

After authentication, decide what each caller may do. A simple, readable approach is a table from method to required role, checked in the same or a second interceptor:

Go Role-based authorization table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice deny by default: a method missing from the table is refused rather than accidentally open. For object-level rules ("only the owner may read this order") the check belongs inside the handler, where you know which object the request names.

API keys, OAuth and service accounts

  • API keys are long random strings stored hashed on the server and looked up per call. Good for server-to-server access and simple developer APIs. Send them in a header such as x-api-key.
  • OAuth 2.0 / OpenID Connect is the standard for user login. The client gets short-lived access tokens from an identity provider and sends them as bearer tokens; the server validates them with the provider's public keys.
  • mTLS identities (see TLS) authenticate services without tokens at all.

Security checklist

  • Send tokens only over TLS; never log them (redact authorization in your logging interceptor).
  • Keep access tokens short-lived and use refresh tokens for longer sessions.
  • Verify signature, expiry, issuer and audience, not just the signature.
  • Return the same generic UNAUTHENTICATED message for every token problem; do not tell attackers whether the signature or the expiry failed.
  • Rate-limit failed attempts at the edge.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A valid token belongs to a reader who calls DeleteAll. Which status is correct?

    The caller is known (authenticated) but not allowed, which is PERMISSION_DENIED.
  2. 2. What does RequireTransportSecurity() returning true do in a PerRPCCredentials implementation?

    It prevents accidental token leaks: the library refuses to attach the credentials unless the channel is secure.
  3. 3. Why does the forged JWT in the demo fail verification?

    The HMAC is computed over header and payload, so any change to the payload invalidates the signature.
  4. 4. What does deny by default mean for authorization?

    Forgetting to add a rule for a new method should fail closed, not leave it open.

Summary

  • Tokens in the authorization metadata entry identify the caller on every call; TLS protects them in transit.
  • Client: credentials.PerRPCCredentials with grpc.WithPerRPCCredentials. Server: an auth interceptor that verifies the token and stores claims in the context.
  • Authentication failures are UNAUTHENTICATED; authorization failures are PERMISSION_DENIED.
  • Verify signature, expiry, issuer and audience; keep tokens short-lived; never log them.
  • Authorize per method with deny by default, and per object inside the handler.

Next: Load Balancing