2

I have a unary interceptor that validates the jwt token and parses the id and role. Now I need to pass these to the service function.

Interceptor

func Unary() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
    log.Printf("--> unary interceptor: %s ", info.FullMethod)

    if info.FullMethod == "/AntmanServer.AntmanUserRoutes/LoginUser" {
        return handler(ctx, req)
    }

    userId, _, err := authorize(ctx)
    if err != nil {
        return fmt.Sprintf("Error : %s", err), err
    }

    //newCtx := metadata.AppendToOutgoingContext(ctx,"id-key", string(userId), "role-key", roles)

    //header := metadata.Pairs("id-key", string(userId), "role-key", roles)
    //grpc.SendHeader(ctx, header)
    newCtx := context.WithValue(ctx, "id-key", string(userId))
    return handler(newCtx, req)
}

}

I have this tried

newCtx := metadata.AppendToOutgoingContext(ctx,"id-key", string(userId), "role-key", roles)

and also this

newCtx := context.WithValue(ctx, "id-key", string(userId))

but none works, how to do this. Thanks in advance.

Ed Randall
  • 6,887
  • 2
  • 50
  • 45
AnswerRex
  • 180
  • 1
  • 1
  • 11
  • what you are doing is correct in principle. Please clarify what "*none works*" means and show the code you're using to get the value in your service function – blackgreen Feb 14 '22 at 15:46

2 Answers2

4

Ok, the problem is solved, thanks to everyone in the comments. I am posting this solution for people coming here in future.

    //interceptor
    md, ok := metadata.FromIncomingContext(ctx)
    if ok {
        md.Append("id-key", string(id))
        md.Append("role-key", role)
    }
    newCtx := metadata.NewIncomingContext(ctx, md)
    return handler(newCtx, req)


   //Rpc function
   md, ok := metadata.FromIncomingContext(ctx)
   Userid := md["id-key"]
   role := md["role-key"]
AnswerRex
  • 180
  • 1
  • 1
  • 11
1

Write in client:

md := metadata.Pairs("key", "value")
ctx := metadata.NewOutgoingContext(context.Background(), md)

And read in server:

md, ok := metadata.FromIncomingContext(ctx)
value := md["key"]
HelloWood
  • 727
  • 4
  • 13
  • It is partially correct as my question was regarding communication between the interceptor and the service function. – AnswerRex Feb 15 '22 at 06:55