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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。