如何通过Cloud Foundry API获取Token?curl调用报错排查
Let's break down why your curl request is failing and fix it step by step:
1. You're using the wrong OAuth endpoint URL
Cloud Foundry's token endpoint isn't hosted on your main CF domain (https://<domain>/oauth/token). Instead, it lives on the UAA (User Account and Authentication) service domain, which is typically https://uaa.<your-cf-domain>/oauth/token. Using the main domain will result in a CF-NotFound error because that endpoint simply doesn't exist there.
To confirm the correct UAA URL: run cf api in your terminal—your API endpoint will look like https://api.<your-domain>, just replace api with uaa to get the valid token endpoint.
2. Your curl request is missing required parameters
The /oauth/token endpoint requires specific form data parameters to authenticate and issue a token. Your current request sends no data at all, which is another critical issue. Depending on the authentication flow you want to use, here are the required parameters:
Password Grant Flow (matches what cf oauth-token uses)
This flow uses your CF username and password to get a token. The default client ID for CF CLI is cf with an empty client secret:
curl 'https://uaa.<your-cf-domain>/oauth/token' -X POST \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'Accept: application/json' \ -d 'grant_type=password&username=your-cf-username&password=your-cf-password&client_id=cf&client_secret='
Client Credentials Flow (for service-to-service auth)
If you're using a dedicated service client, use this flow instead:
curl 'https://uaa.<your-cf-domain>/oauth/token' -X POST \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'Accept: application/json' \ -d 'grant_type=client_credentials&client_id=your-custom-client-id&client_secret=your-client-secret'
3. Minor syntax issue in your original command
Your Accept header is missing a closing quote at the end (-H 'Accept: application/json should be -H 'Accept: application/json'). While this might just be a typo when you shared the command, it would cause curl to throw an error if left uncorrected.
Pro Tip: Mimic the CF CLI's behavior directly
If you want to exactly replicate what cf oauth-token does, run it with verbose mode to see the full request details:
cf oauth-token -v
This will show you the exact URL, headers, and parameters the CLI uses—you can copy those directly into your curl command for guaranteed results.
内容的提问来源于stack exchange,提问作者JKLM

