func (us UsersService) GetToken(username, password string) (string, error) {
	query := url.Values{
		"client_id":     []string{"cf"},
		"redirect_uri":  []string{"https://uaa.cloudfoundry.com/redirect/cf"},
		"response_type": []string{"token"},
	}

	requestPath := url.URL{
		Path:     "/oauth/authorize",
		RawQuery: query.Encode(),
	}
	req := network.Request{
		Method: "POST",
		Path:   requestPath.String(),
		Body: network.NewFormRequestBody(url.Values{
			"username": []string{username},
			"password": []string{password},
			"source":   []string{"credentials"},
		}),
		AcceptableStatusCodes: []int{http.StatusFound},
		DoNotFollowRedirects:  true,
	}

	resp, err := newNetworkClient(us.config).MakeRequest(req)
	if err != nil {
		return "", translateError(err)
	}

	locationURL, err := url.Parse(resp.Headers.Get("Location"))
	if err != nil {
		return "", MalformedResponseError{err}
	}

	locationQuery, err := url.ParseQuery(locationURL.Fragment)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return locationQuery.Get("access_token"), nil
}
Ejemplo n.º 2
0
// GetToken will make a request to UAA to retrieve a client token using the
// "client_credentials" grant type. A client id and secret are required.
func (cs ClientsService) GetToken(id, secret string) (string, error) {
	resp, err := newNetworkClient(cs.config).MakeRequest(network.Request{
		Method:        "POST",
		Path:          "/oauth/token",
		Authorization: network.NewBasicAuthorization(id, secret),
		Body: network.NewFormRequestBody(url.Values{
			"client_id":  []string{id},
			"grant_type": []string{"client_credentials"},
		}),
		AcceptableStatusCodes: []int{http.StatusOK},
	})
	if err != nil {
		return "", translateError(err)
	}

	var response documents.TokenResponse
	err = json.Unmarshal(resp.Body, &response)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return response.AccessToken, nil
}
				Expect(err).NotTo(HaveOccurred())
				Expect(ioutil.ReadAll(body)).To(MatchJSON(`{
					"hello": "goodbye"
				}`))
				Expect(contentType).To(Equal("application/json"))
			})

			It("returns an error when the JSON cannot be encoded", func() {
				_, _, err := network.NewJSONRequestBody(func() {}).Encode()
				Expect(err).To(HaveOccurred())
			})
		})
	})

	Describe("FormRequestBody", func() {
		Describe("Encode", func() {
			It("returns a form URL encoded representation of the given object with proper content type", func() {
				values := url.Values{
					"hello": []string{"goodbye"},
					"black": []string{"white"},
				}

				body, contentType, err := network.NewFormRequestBody(values).Encode()
				Expect(err).NotTo(HaveOccurred())
				Expect(ioutil.ReadAll(body)).To(BeEquivalentTo("black=white&hello=goodbye"))
				Expect(contentType).To(Equal("application/x-www-form-urlencoded"))
			})
		})
	})
})