Set authorization header on grpc stream

This commit is contained in:
Ben Toogood 2020-04-16 15:01:16 +01:00 committed by Vasiliy Tolstov
parent e0f64db92c
commit dfd784d4fa

46
grpc.go
View File

@ -131,21 +131,10 @@ func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.R
// set the content type for the request // set the content type for the request
header["x-content-type"] = req.ContentType() header["x-content-type"] = req.ContentType()
// if the caller specifies using service token or no token // set the authorization header
// was passed with the request, set the service token if opts.ServiceToken || len(header["authorization"]) == 0 {
var srvToken string if h := g.authorizationHeader(); len(h) > 0 {
if g.opts.Auth != nil && g.opts.Auth.Options().Token != nil { header["authorization"] = h
srvToken = g.opts.Auth.Options().Token.AccessToken
}
if (opts.ServiceToken || len(header["authorization"]) == 0) && len(srvToken) > 0 {
header["authorization"] = auth.BearerScheme + srvToken
}
// fall back to using the authorization token set in config,
// this enables the CLI to provide a token
if len(header["authorization"]) == 0 {
if token, err := config.Get("micro", "auth", "token"); err == nil && len(token) > 0 {
header["authorization"] = auth.BearerScheme + token
} }
} }
@ -227,6 +216,13 @@ func (g *grpcClient) stream(ctx context.Context, node *registry.Node, req client
// set the content type for the request // set the content type for the request
header["x-content-type"] = req.ContentType() header["x-content-type"] = req.ContentType()
// set the authorization header
if opts.ServiceToken || len(header["authorization"]) == 0 {
if h := g.authorizationHeader(); len(h) > 0 {
header["authorization"] = h
}
}
md := gmetadata.New(header) md := gmetadata.New(header)
ctx = gmetadata.NewOutgoingContext(ctx, md) ctx = gmetadata.NewOutgoingContext(ctx, md)
@ -313,6 +309,26 @@ func (g *grpcClient) stream(ctx context.Context, node *registry.Node, req client
}, nil }, nil
} }
func (g *grpcClient) authorizationHeader() string {
// if the caller specifies using service token or no token
// was passed with the request, set the service token
var srvToken string
if g.opts.Auth != nil && g.opts.Auth.Options().Token != nil {
srvToken = g.opts.Auth.Options().Token.AccessToken
}
if len(srvToken) > 0 {
return auth.BearerScheme + srvToken
}
// fall back to using the authorization token set in config,
// this enables the CLI to provide a token
if token, err := config.Get("micro", "auth", "token"); err == nil && len(token) > 0 {
return auth.BearerScheme + token
}
return ""
}
func (g *grpcClient) poolMaxStreams() int { func (g *grpcClient) poolMaxStreams() int {
if g.opts.Context == nil { if g.opts.Context == nil {
return DefaultPoolMaxStreams return DefaultPoolMaxStreams