gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/go-grpc-middleware/auth/examples_test.go (about) 1 package grpc_auth_test 2 3 import ( 4 grpcauth "gitee.com/ks-custle/core-gm/go-grpc-middleware/auth" 5 grpcctxtags "gitee.com/ks-custle/core-gm/go-grpc-middleware/tags" 6 "gitee.com/ks-custle/core-gm/grpc" 7 "gitee.com/ks-custle/core-gm/grpc/codes" 8 "gitee.com/ks-custle/core-gm/grpc/status" 9 "gitee.com/ks-custle/core-gm/net/context" 10 ) 11 12 //goland:noinspection GoUnusedGlobalVariable 13 var ( 14 cc *grpc.ClientConn 15 ) 16 17 //goland:noinspection GoUnusedParameter 18 func parseToken(token string) (struct{}, error) { 19 return struct{}{}, nil 20 } 21 22 //goland:noinspection GoUnusedParameter 23 func userClaimFromToken(struct{}) string { 24 return "foobar" 25 } 26 27 // Simple example of server initialization code. 28 func Example_serverConfig() { 29 exampleAuthFunc := func(ctx context.Context) (context.Context, error) { 30 token, err := grpcauth.AuthFromMD(ctx, "bearer") 31 if err != nil { 32 return nil, err 33 } 34 tokenInfo, err := parseToken(token) 35 if err != nil { 36 // grpc.Errorf is deprecated. Use status.Errorf instead. 37 //return nil, grpc.Errorf(codes.Unauthenticated, "invalid auth token: %v", err) 38 return nil, status.Errorf(codes.Unauthenticated, "invalid auth token: %v", err) 39 } 40 grpcctxtags.Extract(ctx).Set("auth.sub", userClaimFromToken(tokenInfo)) 41 newCtx := context.WithValue(ctx, "tokenInfo", tokenInfo) 42 return newCtx, nil 43 } 44 45 _ = grpc.NewServer( 46 grpc.StreamInterceptor(grpcauth.StreamServerInterceptor(exampleAuthFunc)), 47 grpc.UnaryInterceptor(grpcauth.UnaryServerInterceptor(exampleAuthFunc)), 48 ) 49 }