Aidan Feldman
Aidan Feldman

Reputation: 5457

Token error using Cloud Foundry API client credentials

I am trying to create a Hubot plugin that sends notifications for Cloud Foundry events to our chat room, but have been banging my head against API auth for a couple days. Essentially, I am trying to consume:

cf curl /v2/events

but am trying to make the equivalent underlying calls via Node.js rather than through the CLI. From my reading of OAuth2, a read-only not-acting-on-behalf-of-a-user server-side-only app is a good use case for client credentials. I couldn't find a CF client library for Node that supports client credentials so I'm trying to do it myself...unsuccessfully. Here's what I've tried, in bash:

CLIENT_ID=hubot-cf-test
CLIENT_SECRET=mysecret

uaac client add $CLIENT_ID --secret $CLIENT_SECRET --scope uaa.none --authorized_grant_types "client_credentials"
curl -X POST --user "$CLIENT_ID:$CLIENT_SECRET" -d 'grant_type=client_credentials' https://uaa.mycloudfoundry.com/oauth/token

# copy in access_token value from previous response
curl -H "Authorization: Bearer eyJhbGc..." https://api.mycloudfoundry.com/v2/events

which gives me

{
  "code": 1000,
  "description": "Invalid Auth Token",
  "error_code": "CF-InvalidAuthToken"
}

What silly little thing am I doing wrong? Thanks in advance!

P.S. Here is my progress on the Hubot plugin, if anyone's interested.

Upvotes: 0

Views: 2212

Answers (2)

Josh Ghiloni
Josh Ghiloni

Reputation: 1300

Do you have the scope cloud_controller.admin for your hubot-cf-test client? You'll need that to access the event stream, I think.

Upvotes: 1

Patrick Mueller
Patrick Mueller

Reputation: 697

Check your ~/.cf/config.json file. That file is used by the cf command to maintain it's current state. You'll see security tokens in there: AccessToken and RefreshToken.

The AccessToken is what you should be using for CLIENT_SECRET, however that token has a VERY short lifetime - think minutes. Once it's expired, you need to get a new one, using the RefreshToken. So, we need to find an example that shows refreshing the token, that you can model your code after.

The authoritative reference is the source for the cf command itself; there's some of the code for that, here: https://github.com/cloudfoundry/cli/blob/master/cf/api/authentication/authentication.go

If you're more of a Java person, there's some code here: https://github.com/cloudfoundry/cf-java-client/blob/master/cloudfoundry-client-lib/src/main/java/org/cloudfoundry/client/lib/oauth2/OauthClient.java

There's more about the UAA, here: https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-APIs.rst

Upvotes: 1

Related Questions