github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/go-grpc-middleware/auth/examples_test.go (about)

     1  package grpc_auth_test
     2  
     3  import (
     4  	grpc_auth "github.com/hxx258456/ccgo/go-grpc-middleware/auth"
     5  	grpc_ctxtags "github.com/hxx258456/ccgo/go-grpc-middleware/tags"
     6  	"github.com/hxx258456/ccgo/grpc"
     7  	"github.com/hxx258456/ccgo/grpc/codes"
     8  	"github.com/hxx258456/ccgo/net/context"
     9  )
    10  
    11  var (
    12  	cc *grpc.ClientConn
    13  )
    14  
    15  func parseToken(token string) (struct{}, error) {
    16  	return struct{}{}, nil
    17  }
    18  
    19  func userClaimFromToken(struct{}) string {
    20  	return "foobar"
    21  }
    22  
    23  // Simple example of server initialization code.
    24  func Example_serverConfig() {
    25  	exampleAuthFunc := func(ctx context.Context) (context.Context, error) {
    26  		token, err := grpc_auth.AuthFromMD(ctx, "bearer")
    27  		if err != nil {
    28  			return nil, err
    29  		}
    30  		tokenInfo, err := parseToken(token)
    31  		if err != nil {
    32  			return nil, grpc.Errorf(codes.Unauthenticated, "invalid auth token: %v", err)
    33  		}
    34  		grpc_ctxtags.Extract(ctx).Set("auth.sub", userClaimFromToken(tokenInfo))
    35  		newCtx := context.WithValue(ctx, "tokenInfo", tokenInfo)
    36  		return newCtx, nil
    37  	}
    38  
    39  	_ = grpc.NewServer(
    40  		grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(exampleAuthFunc)),
    41  		grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(exampleAuthFunc)),
    42  	)
    43  }