gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-grpc-middleware/auth/metadata.go (about)

     1  // Copyright 2016 Michal Witkowski. All Rights Reserved.
     2  // See LICENSE for licensing terms.
     3  
     4  package grpc_auth
     5  
     6  import (
     7  	"gitee.com/ks-custle/core-gm/grpc/status"
     8  	"strings"
     9  
    10  	"gitee.com/ks-custle/core-gm/go-grpc-middleware/util/metautils"
    11  	"gitee.com/ks-custle/core-gm/grpc/codes"
    12  	"gitee.com/ks-custle/core-gm/net/context"
    13  )
    14  
    15  var (
    16  	headerAuthorize = "authorization"
    17  )
    18  
    19  // AuthFromMD is a helper function for extracting the :authorization header from the gRPC metadata of the request.
    20  //
    21  // It expects the `:authorization` header to be of a certain scheme (e.g. `basic`, `bearer`), in a
    22  // case-insensitive format (see rfc2617, sec 1.2). If no such authorization is found, or the token
    23  // is of wrong scheme, an error with gRPC status `Unauthenticated` is returned.
    24  func AuthFromMD(ctx context.Context, expectedScheme string) (string, error) {
    25  	val := metautils.ExtractIncoming(ctx).Get(headerAuthorize)
    26  	if val == "" {
    27  		// `grpc.Errorf` is deprecated. use status.Errorf instead.
    28  		//return "", grpc.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    29  		return "", status.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    30  	}
    31  	splits := strings.SplitN(val, " ", 2)
    32  	if len(splits) < 2 {
    33  		// `grpc.Errorf` is deprecated. use status.Errorf instead.
    34  		//return "", grpc.Errorf(codes.Unauthenticated, "Bad authorization string")
    35  		return "", status.Errorf(codes.Unauthenticated, "Bad authorization string")
    36  	}
    37  	if strings.ToLower(splits[0]) != strings.ToLower(expectedScheme) {
    38  		// `grpc.Errorf` is deprecated. use status.Errorf instead.
    39  		//return "", grpc.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    40  		return "", status.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    41  	}
    42  	return splits[1], nil
    43  }