Go 中的 gRPC 授权
在 gRPC 服务中,每次调用都会指定一个完整的方法名,例如 /library.v1.BookService/DeleteBook。这使得方法级授权变得简单:决定哪些角色可以调用哪些方法,并在处理程序运行之前通过服务器拦截器进行检查。本教程使用 Casbin 在 Go 中实现了这一点,涵盖了一元调用和流式调用。
1. 定义服务
示例是一个小型图书馆服务。将此保存为 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 {}
使用 protoc(或 buf generate)生成 Go 代码:
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. 编写 Model
将其保存为 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:每个请求包含调用者和完整的 gRPC 方法名。g = _, _:可以将调用者分配给角色,也可以将角色分配给其他角色。keyMatch允许规则以*结尾,因此一行规则可以覆盖某个服务的所有方法。
3. 编写策略
将其保存为 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
reader 可以调用 GetBook,librarian 还可以调用 CreateBook,而 admin 可以调用 BookService 的所有方法,包括后来添加的方法。角色之间的 g 行构建了层级结构,因此每个角色只需列出其级别上新增的权限。
4. 编写拦截器
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,已认证但没有权限的调用者会收到 PermissionDenied,这是 gRPC 客户端和网关所期望的行为。
为了保持示例简短,这里使用 x-user 元数据。Casbin 仅处理授权。在真实的服务中,应验证来自 authorization 元数据的令牌,或者在使用 mTLS 时通过 peer.FromContext 从客户端证书获取身份。如果已有认证拦截器执行了此操作,请将其链接在授权拦截器之前。
5. 在服务器上注册它们
package main
import (
"context"
"log"
"net"
"github.com/casbin/casbin/v3"
"google.golang.org/grpc"
libraryv1 "example.com/library/gen/library/v1"
)
type bookService struct {
libraryv1.UnimplementedBookServiceServer
}
func (bookService) GetBook(ctx context.Context, req *libraryv1.GetBookRequest) (*libraryv1.Book, error) {
return &libraryv1.Book{Id: req.GetId(), Title: "The Go Programming Language"}, nil
}
func (bookService) CreateBook(ctx context.Context, req *libraryv1.CreateBookRequest) (*libraryv1.Book, error) {
return &libraryv1.Book{Id: "2", Title: req.GetTitle()}, nil
}
func (bookService) DeleteBook(ctx context.Context, req *libraryv1.DeleteBookRequest) (*libraryv1.DeleteBookResponse, error) {
return &libraryv1.DeleteBookResponse{}, nil
}
func main() {
e, err := casbin.NewEnforcer("model.conf", "policy.csv")
if err != nil {
log.Fatal(err)
}
s := grpc.NewServer(
grpc.ChainUnaryInterceptor(UnaryAuthz(e)),
grpc.ChainStreamInterceptor(StreamAuthz(e)),
)
libraryv1.RegisterBookServiceServer(s, bookService{})
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatal(err)
}
log.Fatal(s.Serve(lis))
}
grpc.ChainUnaryInterceptor 和 grpc.ChainStreamInterceptor 接受多个拦截器,因此可以在授权检查旁边添加日志记录、指标监控和认证 功能。
6. 测试一下
启动服务器:
go run ./server
此客户端以四个不同用户身份调用所有方法:
package main
import (
"context"
"fmt"
"log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
libraryv1 "example.com/library/gen/library/v1"
)
func main() {
conn, err := grpc.NewClient("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
client := libraryv1.NewBookServiceClient(conn)
for _, user := range []string{"alice", "bob", "carol", "dave"} {
ctx := metadata.AppendToOutgoingContext(context.Background(), "x-user", user)
_, getErr := client.GetBook(ctx, &libraryv1.GetBookRequest{Id: "1"})
_, createErr := client.CreateBook(ctx, &libraryv1.CreateBookRequest{Title: "New book"})
_, deleteErr := client.DeleteBook(ctx, &libraryv1.DeleteBookRequest{Id: "1"})
fmt.Printf("%-6s GetBook=%-16v CreateBook=%-16v DeleteBook=%v\n", user,
status.Code(getErr), status.Code(createErr), status.Code(deleteErr))
}
}
go run ./client
alice GetBook=OK CreateBook=OK DeleteBook=OK
bob GetBook=OK CreateBook=OK DeleteBook=PermissionDenied
carol GetBook=OK CreateBook=PermissionDenied DeleteBook=PermissionDenied
dave GetBook=PermissionDenied CreateBook=PermissionDenied DeleteBook=PermissionDenied
使用 grpcurl 时,通过标头传递用户信息:grpcurl -plaintext -H "x-user: bob" ...。
进阶内容
- 公开方法。 健康检查和服务器反射通常不需要用户身份。请在
authorize函数的顶部尽早返回,例如if strings.HasPrefix(fullMethod, "/grpc.health.v1.Health/") { return nil }。 - 基于记录的规则。 拦截器在处理器运行前只能看到方法名。依赖于具体记录的规则(例如“图书馆员只能删除自己分馆的书籍”)应放在加载记录后的处理器中;请参阅 ABAC 教程。
- 多租户服务。 将租户作为第三个参数从元数据中传递,并使用 带域名的 RBAC。
- 将策略存储在数据库中。 用 适配器 替换
policy.csv,并在多个副本提供相同服务时添加 监视器。 - HTTP API。 对于 Go 中的 REST 端点,请参阅 Go 中使用 Gin 实现 RBAC。
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.