Using curl to access protected API

Learn how to access an API with Keycloak security-enabled by using the curl tool to obtain an access token.
  1. Create an instance of Keycloak following the indicated procedures.
  2. Run the microservice payment.
  3. Make sure you have registered a user in Keycloak and obtained the Realm credentials.
  4. To obtain the authentication token through curl, it is necessary to make a post in the Keycloak API informing the parameters: username, password, client_id, client_secret.

a) After obtaining the parameters

1
curl -X POST http://localhost:8080/realms/devprime/protocol/openid-connect/token -H 'Content-Type: application/x-www-form-urlencoded' -d username=$username -d password=$password -d grant_type=password -d client_id=$client -d client_secret=<secret> --insecure

b) After executing it, you should get the result as shown in the example below.

1
{"access_token":"eyJhbGciOiJSUzI1NDdfOE1DdTVvSU5OR1pyN3BIeV9jIn0","expires_in":300,"refresh_expires_in":1800,"refresh_token":"eyn0.g3GJR-jdc0TpsL9E","token_type":"Bearer","not-before-policy":0,"session_state":"21d413e9-cffa-47227bec6","scope":"profile email"}

In this example, we’ve reduced the size of the result Access Token to make it easier to see. There are some tools that allow you to view the JSON Web Token if you want to inspect the Keycloak result.

c) Get the value of the access token and mount the query to perform a GET on the protected API entering the “Authorization: Bearer” parameter in the Header.

1
2
curl -X GET https://localhost:5003/v1/payment -H "Authorization: Bearer eyJhbGciOiJSUzI1NDdfOE1DdTVvSU5OR1pyN3BIeV9jIn0" -H 'accept: */*'
grant_type=password -d client_id=$client -d client_secret=<secret> --insecure

d) The same example can be repeated to perform a POST to the protected API.

1
curl -X 'POST' 'https://localhost:5003/v1/payment' -H "Accept:application/json"  -H "Content-Type:application/json" -H "Authorization: Bearer eyJhbGciOiJSUzI1NDdfOE1DdTVvSU5OR1pyN3BIeV9jIn0" -d '{\"customerName\": \"Ramon\", \"orderID\": \"3fa85f64-5717-4562-b3fc-2c963f66afa6\", \"value\": \"0\"}'
Last modified October 17, 2023 (e38ae05b)