This grant is suitable for machine-to-machine communication where the application is the owner of the access token. This means that you store your OAuth client credentials on your machine (server) and users of your application would make requests through your server.
The flow of the Client Credentials grant is fairly simple. You use your client credentials to request an access token from the authentication server and then use that access token in your requests to the API server. A more in depth explanation follows below.
Client Credentials authentication flow
1. Requesting an access token.
Send a POST request to /access-token. The body must contain the following:
- grant_type with the value client_credentials
- client_id with the client id as provided by MyParcel.com
- client_secret with the client secret as provided by MyParcel.com
Don’t forget to set the Content-Type header to application/json.
2. Response with new access token.
The authentication server will respond with the following body:
- token_type with the value Bearer
- expires_in with an integer representing the time to live (TTL) of the access token
- access_token the access token itself
You can now store this access token on your system to be attached to all MyParcel.com API calls.
3. Making a request to the MyParcel.com API
To make a request to the MyParcel.com API you have to add your access token to the request. You can do this by setting the access token as the Bearer token in the Authorisation header.
All requests to the MyParcel.com API with an expired or otherwise invalid access token will be rejected. A convenient way to make sure you have an access token that has not expired is to let the server periodically request a new access token before the previous one expires. The overlap between the different tokens will not cause a problem with running requests.
4. The server response
When using a valid token, the server will just give the expected response.
Expired Access Token
Another way to handle expired access tokens (aside from periodically requesting a new one) is to queue the incoming requests when you application notices that the access token has expired. Below is an example flow of how you could set this up.
Since the access token is a JSON Web Token (JWT), you can simply parse it with your favourite JWT library and get the exact UNIX timestamp when the access token expires. This means that you could queue your requests either on the user’s device (step 1) or on your server (step 2) while a side job requests a new access token. When the new access token is received by the server it can be attached to all queued requests before they are executed again.