gRPC 基于 HTTP/2 多路复用传输 Protobuf 消息,默认不加密。生产环境必须启用 mTLS 双向证书认证,并通过 Unary/Stream 拦截器在服务端统一校验 JWT 或 SPIFFE 身份,避免在每个 RPC 方法中重复鉴权逻辑。
一、Go gRPC 服务端 mTLS 与鉴权拦截器
go
import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func authInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok || len(md.Get("authorization")) == 0 {
return nil, status.Error(codes.Unauthenticated, "missing token")
}
if err := verifyJWT(md.Get("authorization")[0]); err != nil {
return nil, status.Error(codes.PermissionDenied, "invalid token")
}
return handler(ctx, req)
}
creds, _ := credentials.NewServerTLSFromFile("server.crt", "server.key")
srv := grpc.NewServer(
grpc.Creds(creds),
grpc.UnaryInterceptor(authInterceptor),
)