Using curl to access protected API
Learn how to access a security-enabled API
- Create an instance of Keycloak following the steps indicated.
- Run the payment.
- Make sure you have registered a user in Keycloak and obtained Realm credentials.
- 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, 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 have reduced the size of the result Access Token to make it easier to see. There are a few tools that allow you to view the JSON Web Token if you want to view the Keycloak result.
c) Get the value of the access token and assemble the query to perform a GET in the protected API entering the parameter “Authorization: Bearer” 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 in 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 August 20, 2024 (2f9802da)