github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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  	"strings"
     8  
     9  	"github.com/hxx258456/ccgo/go-grpc-middleware/util/metautils"
    10  	"github.com/hxx258456/ccgo/grpc"
    11  	"github.com/hxx258456/ccgo/grpc/codes"
    12  	"github.com/hxx258456/ccgo/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  		return "", grpc.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    28  
    29  	}
    30  	splits := strings.SplitN(val, " ", 2)
    31  	if len(splits) < 2 {
    32  		return "", grpc.Errorf(codes.Unauthenticated, "Bad authorization string")
    33  	}
    34  	if strings.ToLower(splits[0]) != strings.ToLower(expectedScheme) {
    35  		return "", grpc.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    36  	}
    37  	return splits[1], nil
    38  }