github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/api/uaa/auth.go (about) 1 package uaa 2 3 import ( 4 "net/http" 5 "net/url" 6 "strings" 7 8 "code.cloudfoundry.org/cli/api/uaa/constant" 9 "code.cloudfoundry.org/cli/api/uaa/internal" 10 ) 11 12 // AuthResponse contains the access token and refresh token which are granted 13 // after UAA has authorized a user. 14 type AuthResponse struct { 15 AccessToken string `json:"access_token"` 16 RefreshToken string `json:"refresh_token"` 17 } 18 19 // Authenticate sends a username and password to UAA then returns an access 20 // token and a refresh token. 21 func (client Client) Authenticate(ID string, secret string, grantType constant.GrantType) (string, string, error) { 22 requestBody := url.Values{ 23 "grant_type": {string(grantType)}, 24 } 25 switch grantType { 26 case constant.GrantTypeClientCredentials: 27 requestBody.Set("client_id", ID) 28 requestBody.Set("client_secret", secret) 29 default: 30 requestBody.Set("username", ID) 31 requestBody.Set("password", secret) 32 } 33 34 request, err := client.newRequest(requestOptions{ 35 RequestName: internal.PostOAuthTokenRequest, 36 Header: http.Header{ 37 "Content-Type": {"application/x-www-form-urlencoded"}, 38 }, 39 Body: strings.NewReader(requestBody.Encode()), 40 }) 41 42 if err != nil { 43 return "", "", err 44 } 45 46 if grantType == constant.GrantTypePassword { 47 request.SetBasicAuth(client.config.UAAOAuthClient(), client.config.UAAOAuthClientSecret()) 48 } 49 50 responseBody := AuthResponse{} 51 response := Response{ 52 Result: &responseBody, 53 } 54 55 err = client.connection.Make(request, &response) 56 return responseBody.AccessToken, responseBody.RefreshToken, err 57 }