github.com/vmware/govmomi@v0.43.0/govc/sso/client.go (about) 1 /* 2 Copyright (c) 2019 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package sso 18 19 import ( 20 "context" 21 "log" 22 "os" 23 24 "github.com/vmware/govmomi/govc/flags" 25 "github.com/vmware/govmomi/ssoadmin" 26 "github.com/vmware/govmomi/sts" 27 "github.com/vmware/govmomi/vim25/soap" 28 ) 29 30 func WithClient(ctx context.Context, cmd *flags.ClientFlag, f func(*ssoadmin.Client) error) error { 31 vc, err := cmd.Client() 32 if err != nil { 33 return err 34 } 35 36 c, err := ssoadmin.NewClient(ctx, vc) 37 if err != nil { 38 return err 39 } 40 c.RoundTripper = cmd.RoundTripper(c.Client) 41 42 // SSO admin server has its own session manager, so the govc persisted session cookies cannot 43 // be used to authenticate. There is no SSO token persistence in govc yet, so just use an env 44 // var for now. If no GOVC_LOGIN_TOKEN is set, issue a new token. 45 token := os.Getenv("GOVC_LOGIN_TOKEN") 46 header := soap.Header{ 47 Security: &sts.Signer{ 48 Certificate: vc.Certificate(), 49 Token: token, 50 }, 51 } 52 53 if token == "" { 54 tokens, cerr := sts.NewClient(ctx, vc) 55 if cerr != nil { 56 return cerr 57 } 58 59 req := sts.TokenRequest{ 60 Certificate: vc.Certificate(), 61 Userinfo: cmd.Session.URL.User, 62 } 63 64 header.Security, cerr = tokens.Issue(ctx, req) 65 if cerr != nil { 66 return cerr 67 } 68 } 69 70 if err = c.Login(c.WithHeader(ctx, header)); err != nil { 71 return err 72 } 73 74 defer func() { 75 if err := c.Logout(ctx); err != nil { 76 log.Printf("user logout error: %v", err) 77 } 78 }() 79 80 return f(c) 81 }