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