github.com/vmware/govmomi@v0.51.0/cli/sso/client.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package sso
     6  
     7  import (
     8  	"context"
     9  	"log"
    10  	"os"
    11  
    12  	"github.com/vmware/govmomi/cli/flags"
    13  	"github.com/vmware/govmomi/ssoadmin"
    14  	"github.com/vmware/govmomi/sts"
    15  	"github.com/vmware/govmomi/vim25/soap"
    16  )
    17  
    18  func WithClient(ctx context.Context, cmd *flags.ClientFlag, f func(*ssoadmin.Client) error) error {
    19  	vc, err := cmd.Client()
    20  	if err != nil {
    21  		return err
    22  	}
    23  
    24  	c, err := ssoadmin.NewClient(ctx, vc)
    25  	if err != nil {
    26  		return err
    27  	}
    28  	c.RoundTripper = cmd.RoundTripper(c.Client)
    29  
    30  	// SSO admin server has its own session manager, so the govc persisted session cookies cannot
    31  	// be used to authenticate.  There is no SSO token persistence in govc yet, so just use an env
    32  	// var for now.  If no GOVC_LOGIN_TOKEN is set, issue a new token.
    33  	token := os.Getenv("GOVC_LOGIN_TOKEN")
    34  	header := soap.Header{
    35  		Security: &sts.Signer{
    36  			Certificate: vc.Certificate(),
    37  			Token:       token,
    38  		},
    39  	}
    40  
    41  	if token == "" {
    42  		tokens, cerr := sts.NewClient(ctx, vc)
    43  		if cerr != nil {
    44  			return cerr
    45  		}
    46  
    47  		req := sts.TokenRequest{
    48  			Certificate: vc.Certificate(),
    49  			Userinfo:    cmd.Session.URL.User,
    50  		}
    51  
    52  		header.Security, cerr = tokens.Issue(ctx, req)
    53  		if cerr != nil {
    54  			return cerr
    55  		}
    56  	}
    57  
    58  	if err = c.Login(c.WithHeader(ctx, header)); err != nil {
    59  		return err
    60  	}
    61  
    62  	defer func() {
    63  		if err := c.Logout(ctx); err != nil {
    64  			log.Printf("user logout error: %v", err)
    65  		}
    66  	}()
    67  
    68  	return f(c)
    69  }