douzhuang2570 2019-01-30 09:34
浏览 254

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?

  • 写回答

1条回答 默认 最新

  • dongyan1625 2019-02-01 18:23
    关注

    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()
    
    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集