During development, it happens that you quickly want to try out a RESTful request. If you are running this request against an OAuth2 protected resource, you’ll need an access_token. So what is the easiest approach to get one? Unfortunately, OAuth2 is not supported just like Basic Authentication in the browser. The easiest option I’ve found is using CURL, the command-line utility for HTTP requests.
To get an access token for user demo and password 1234, I simply use the OAuth2 Resource Owner Password flow. Keep in mind, the token endpoint would need to be HTTPS in production, but for development this is fine:
|
1 |
curl -X POST -d "client_id=mobile_android&client_secret=secret&grant_type=password&username=demo&password=1234" http://localhost:9001/rest/oauth/token |
The responsen will be the usual one:
|
1 2 3 4 5 6 |
{ "access_token": "a503faf9-45b5-4fec-8334-337284a66ea4", "token_type": "bearer", "refresh_token": "486adfde-757b-4d37-81d7-446c2ec4bd91", "expires_in": 43199 } |
Next, if you want to access a protected resource you have to pass the Authorization header. Let’s access our “current user” resource:
|
1 |
curl --header "Authorization: Bearer a503faf9-45b5-4fec-8334-337284a66ea4" http://localhost:9001/rest/v1/electronics/custoers/current |
And the Response will be similar to this:
|
1 2 3 4 5 6 7 |
{ "uid": "demo", "name": "demo", "firstName": "Klaus", "lastName": "Demokunde" ... } |
I hope you find this pretty straightforward, too!
I got the following response for my client_crednetials access token request.
How do I debug this? I got a 443 error.. I did try a get request for the oauth/token url and I got a 404 error from the host site so I understand that the request hits the web server and that I am not blocked by any firewall rule.
curl -X POST -d “client_id=qwer1234&client_secret=fdswer234&grant_type=client_credentials&scope=qwer:read” https://api.xyz.com/oauth/token
curl: (7) Failed to connect to api.xyz.com port 443: Timed out