Accessing an OAuth 2.0 protected web API requires an access token to be passed in the request’s authorization header.
From the terminal, if you do not already have an access token, this would mean hitting a given endpoint, copying the access token, and using it in subsequent requests. All of these may seem fine if manually copying the token from the response is not a problem for you, but there are other situations where that flow may not be practical such as having an unattended bash script which is required to interact with an API where each session requires a fresh access token.
OAuth 2.0 requires a
client(the application) to obtain an access token from an
authorization serveron behalf of a
resource owner(the user) to access resources from a
resource server(the platform).
To learn more, you can access the proposed standard and there is a great learning resource at oauth.com.
To accomplish this, you will need:
- an HTTP client to make HTTP requests on the terminal, e.g., cURL or HTTPie . The latter will be used as it is friendlier compared to cURL in terms of accessing APIs. For example, to issue a POST request to a periods endpoint with some JSON payload on a local machine running on port 9000 is simply
http :9000/v1/periods name="Quarter 1" abbreviation=Q1 type=Quarterly
- a JSON processor with the ability to filter a JSON data. jq is just the perfect tool for that
- a way to remove the enclosing double quotes (“) that wraps JSON string values. The translate (tr) command in Linux has that feature using the
tr -d '"'
With everything set, running the commands below extracts the access_token and exports it to the variable token
export token=$(http -a web:web :9000/oauth/token \ email@example.com password=xxx grant_type=password \ | jq '.access_token' | tr -d '"')
The password grant type is being used because the client is a trusted client as I am the same developer building the frontend application to consume the API.
The client credentials is specified in the format: client_id:client_secret.
The example above uses web for both the client_id and the client_secret.
Accessing the protected resources is achieved by adding the bearer token in the authorization header as shown in the example below.
http :9000/v1/documents Authorization:"Bearer $token"