I'm new to GO and I'm following https://parthdesai.me/articles/2016/05/20/go-rpc-server/ to build a simple RPC server&client. In this article, it says
Benefit of this approach (HTTP) is, you can perform authentication of client easily, before allowing RPC, using any authentication method supported by HTTP.
But the example on the page doesn't seem to perform it. I have searched it on StackOverflow, and found Passing authentication details with a JSON-RPC call saying
There's two ways to accomplish what you want: either implement an HTTP-speaking
io.ReadWriteCloser
and use as in your example or implement anrpc.ClientCodec
that does the HTTP basic auth and use in conjunction withrpc.NewClientWithCodec
.
However, I still don't know how to do it. Could I have some example code (may be Basic Authentication
method)?
CodePudding user response:
Using transcoding and checking authentication in gRPC middleware is better for http server over gRPC using gRPC gateway.
https://cloud.google.com/endpoints/docs/grpc/transcoding
To get authorization in headers, use gRPC middleware and get from context with gRPC MD.
srv := grpc.NewServer(exampleJwtMiddleware())
func exampleJwtMiddleware() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
token, err := extractHeaderFromContext(ctx, "Authorization")
// do sometings...
return handler(ctx, req)
}
}
func extractHeaderFromContext(ctx context.Context, header string) ([]string, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, ERROR_NO_HEADER_IN_REQUEST
}
foundedHeaders, ok := md[header]
if !ok {
return nil, ERROR_NO_HEADER_IN_REQUEST
}
return foundedHeaders, nil
}