...

Source file src/github.com/grpc-ecosystem/go-grpc-middleware/auth/metadata.go

Documentation: github.com/grpc-ecosystem/go-grpc-middleware/auth

     1  // Copyright 2016 Michal Witkowski. All Rights Reserved.
     2  // See LICENSE for licensing terms.
     3  
     4  package grpc_auth
     5  
     6  import (
     7  	"context"
     8  	"strings"
     9  
    10  	"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
    11  	"google.golang.org/grpc/codes"
    12  	"google.golang.org/grpc/status"
    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 "", status.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    28  	}
    29  	splits := strings.SplitN(val, " ", 2)
    30  	if len(splits) < 2 {
    31  		return "", status.Errorf(codes.Unauthenticated, "Bad authorization string")
    32  	}
    33  	if !strings.EqualFold(splits[0], expectedScheme) {
    34  		return "", status.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
    35  	}
    36  	return splits[1], nil
    37  }
    38  

View as plain text