Skip to main content

gRPC Middleware

Using authorization middleware when building gRPC servers focuses the responsibility of making authorization decisions to a single component instead of fragmenting the logic across many service methods.

The middleware can be configured to retrieve authorization information, such as user identity, from incoming messages and streams.

Creating Middleware#

Creating middleware requires two arguments: an authorizer client, and a Policy that identifies the authorization policy to be applied, the decision rule to evaluate, and optionally a path to a policy module. If a path isn't provided, the middleware infers the policy path from the incoming request's URL. This behavior too can be further customized to fit other naming schemes.

import (    middleware "")
// Create gRPC := middleware.New(    authClient,    mw.Policy{        ID:       "<Aserto policy ID>",        Decision: "allowed",             // Name of the policy rule to evaluate.    },)

Configuring Middleware#

Middleware can be configured to extract authorization information from incoming requests. This information includes:

  1. Identity: the identity of the caller.
  2. Policy Path: the policy module to evaluate (e.g. "peoplefinder.GET.api.users.__id").
  3. Resource: contextual information about the resource being accessed.


Identity information is set on the middleware's .Identity.

For example, to read a subject name from a "username" context value on the incoming request (presumabely, set by some authentication middleware):


Or, to configure the middleware to identify callers using a JWT in the "identity" metadata key on the incoming request context: request context:


Policy Path#

If a policy path isn't specified when the middleware is created, it will be inferred from the request method, replacing path separators (/) with dots(.) (e.g. /service/method becomes, service.method).

To provide your own logic for determining the policy path use:

mw.WithPolicyPathMapper(    func(r *http.Request) string {        // custom logic inspects the request and returns the policy path.    },)


Resource information can be added to authorization requests using .WithResourceMapper():

mw.WithResourceMapper(    func(r *http.Request) *structpb.Struct {        resourceContext, err := structpb.NewStruct(map[string]string{            "ownerId": GetOwner(r),  // Custom function to retrieve the owner of the resource being accessed.        })        if err != nil {            return resourceContext        }
        return nil    },)

Connecting Middleware#

With a configured middleware in hand, all that's left is connecting it to your gRPC server:

// Create gRPC server with middleware.s := grpc.NewServer(    grpc.UnaryInterceptor(mw.Unary),    grpc.StreamInterceptor(mw.Stream),)