Posted by & filed under APIs, hybris, oauth2, Testing.

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:

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:

{
  "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:

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:

{
  "uid": "demo",
  "name": "demo",
  "firstName": "Klaus",
  "lastName": "Demokunde"
  ...
}

I hope you find this pretty straightforward, too!
 

Leave a Reply

  • (will not be published)