github.com/pivotal-cf/go-pivnet/v6@v6.0.2/uaa.go (about) 1 package pivnet 2 3 import ( 4 "bytes" 5 "crypto/tls" 6 "encoding/json" 7 "fmt" 8 "net/http" 9 "time" 10 ) 11 12 type AuthResp struct { 13 Token string `json:"access_token"` 14 } 15 16 type TokenFetcher struct { 17 Endpoint string 18 RefreshToken string 19 SkipSSLValidation bool 20 UserAgent string 21 } 22 23 func NewTokenFetcher(endpoint, refreshToken string, skipSSLValidation bool, userAgent string) *TokenFetcher { 24 return &TokenFetcher{endpoint, refreshToken, skipSSLValidation, userAgent } 25 } 26 27 func (t TokenFetcher) GetToken() (string, error) { 28 httpClient := &http.Client{ 29 Timeout: 60 * time.Second, 30 Transport: &http.Transport{ 31 TLSClientConfig: &tls.Config{ 32 InsecureSkipVerify: t.SkipSSLValidation, 33 }, 34 Proxy: http.ProxyFromEnvironment, 35 }, 36 } 37 body := AuthBody{RefreshToken: t.RefreshToken} 38 b, err := json.Marshal(body) 39 if err != nil { 40 return "", fmt.Errorf("failed to marshal API token request body: %s", err.Error()) 41 } 42 req, err := http.NewRequest("POST", t.Endpoint+"/authentication/access_tokens", bytes.NewReader(b)) 43 req.Header.Add("Content-Type", "application/json") 44 45 if t.UserAgent != "" { 46 req.Header.Add("User-Agent", t.UserAgent) 47 } 48 49 if err != nil { 50 return "", fmt.Errorf("failed to construct API token request: %s", err.Error()) 51 } 52 53 resp, err := httpClient.Do(req) 54 if err != nil { 55 return "", fmt.Errorf("API token request failed: %s", err.Error()) 56 } 57 58 defer resp.Body.Close() 59 60 if resp.StatusCode != http.StatusOK { 61 return "", fmt.Errorf("failed to fetch API token - received status %v", resp.StatusCode) 62 } 63 64 var response AuthResp 65 err = json.NewDecoder(resp.Body).Decode(&response) 66 if err != nil { 67 return "", fmt.Errorf("failed to decode API token response: %s", err.Error()) 68 } 69 70 return response.Token, nil 71 }