gRPC授权方法

I work on go grpc service and implementing authorization. Literally, have to allow or forbid access to gprc methods base on JWT claims.

I do JWT parsing on grpc.UnaryServerInterceptor level - extracting claims and populate context with value, unauthenticated if there is no jwt or it is incorrect.

func (s *Server) GetSomething(ctx context.Context, req *GetSomething Request) (*GetSomething Response, error) {
    if hasAccessTo(ctx, req.ID) {
        //some work here
    }
}

func hasAccessTo(ctx context.Context, string id) {
    value := ctx.Value(ctxKey).(MyStruct)
    //some work here

}

So I wonder if there is some common practice for authorization/authentication to avoid boilerplate code in each grpc server method?

You can call a to a UnaryInterceptor like so if you want to verify the jwt on every request

// middleware for each rpc request. This function verifies the client has the correct "jwt".
func authInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    meta, ok := metadata.FromIncomingContext(ctx)
    if !ok {
        return nil, status.Error(codes.Unauthenticated, "INTERNAL_SERVER_ERROR")
    }
    if len(meta["jwt"]) != 1 {
        return nil, status.Error(codes.Unauthenticated, "INTERNAL_SERVER_ERROR")
    }

    // if code here to verify jwt is correct. if not return nil and error by accessing meta["jwt"][0]

    return handler(ctx, req) // go to function.
}

In your context from the client use the metadata to pass the jwt string and verify.

In Your main function remember to register it like so

// register server
myService := grpc.NewServer(
    grpc.UnaryInterceptor(authInterceptor), // use auth interceptor middleware
)
pb.RegisterTheServiceServer(myService, &s)
reflection.Register(myService)

Your client would need to call your server like this:

// create context with token and timeout
ctx, cancel := context.WithTimeout(metadata.NewOutgoingContext(context.Background(), metadata.New(map[string]string{"jwt": "myjwtstring"})), time.Second*1)
defer cancel()