gRPC Authorization in Go
In a gRPC service, every call names a full method such as /library.v1.BookService/DeleteBook. That makes method-level authorization simple: decide which roles may call which methods, and check it in a server interceptor before the handler runs. This tutorial does that in Go with Casbin, for both unary and streaming calls.
1. Define the service
The example is a small library service. Save this as proto/library/v1/library.proto:
syntax = "proto3";
package library.v1;
option go_package = "example.com/library/gen/library/v1;libraryv1";
service BookService {
rpc GetBook(GetBookRequest) returns (Book);
rpc CreateBook(CreateBookRequest) returns (Book);
rpc DeleteBook(DeleteBookRequest) returns (DeleteBookResponse);
}
message Book {
string id = 1;
string title = 2;
}
message GetBookRequest {
string id = 1;
}
message CreateBookRequest {
string title = 1;
}
message DeleteBookRequest {
string id = 1;
}
message DeleteBookResponse {}
Generate the Go code with protoc (or buf generate):
go mod init example.com/library
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
protoc -Iproto --go_out=. --go_opt=module=example.com/library --go-grpc_out=. --go-grpc_opt=module=example.com/library proto/library/v1/library.proto
go get github.com/casbin/casbin/v3 google.golang.org/grpc
2. Write the model
Save this as model.conf:
[request_definition]
r = sub, method
[policy_definition]
p = sub, method
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.method, p.method)
r = sub, method: each request is a caller and the full gRPC method name.g = _, _: callers can be assigned to roles, and roles to other roles.keyMatchlets a rule end in*, so one line can cover every method of a service.
3. Write the policy
Save this as policy.csv:
p, reader, /library.v1.BookService/GetBook
p, librarian, /library.v1.BookService/CreateBook
p, admin, /library.v1.BookService/*
g, librarian, reader
g, admin, librarian
g, alice, admin
g, bob, librarian
g, carol, reader
A reader may call GetBook, a librarian may also call CreateBook, and an admin may call every method of BookService, including methods added later. The g lines between roles build the hierarchy, so each role lists only what is new at its level.
4. Write the interceptors
package main
import (
"context"
"github.com/casbin/casbin/v3"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// authorize asks Casbin whether the caller may invoke fullMethod, such as /library.v1.BookService/DeleteBook.
func authorize(ctx context.Context, e *casbin.Enforcer, fullMethod string) error {
// Replace this with the identity from your authentication layer,
// such as a verified JWT in the "authorization" metadata or the client's mTLS certificate.
md, _ := metadata.FromIncomingContext(ctx)
users := md.Get("x-user")
if len(users) == 0 {
return status.Error(codes.Unauthenticated, "missing user")
}
allowed, err := e.Enforce(users[0], fullMethod)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
if !allowed {
return status.Errorf(codes.PermissionDenied, "%s may not call %s", users[0], fullMethod)
}
return nil
}
func UnaryAuthz(e *casbin.Enforcer) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if err := authorize(ctx, e, info.FullMethod); err != nil {
return nil, err
}
return handler(ctx, req)
}
}
func StreamAuthz(e *casbin.Enforcer) grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := authorize(ss.Context(), e, info.FullMethod); err != nil {
return err
}
return handler(srv, ss)
}
}
Unauthenticated callers get Unauthenticated, and authenticated callers without the permission get PermissionDenied, which is what gRPC clients and gateways expect.
The x-user metadata keeps the example short. Casbin handles authorization only. In a real service, verify a token from the authorization metadata, or take the identity from the client certificate with peer.FromContext when you use mTLS. If an authentication interceptor already does that, chain it before the authorization interceptor.