At e.GO Mobile we implemented an API cluster with many microservices, similar to Microsoft’s Graph API.

We almost use OAuth2 for authentication in order to generate corresponding JSON Web Tokens (JWT) for the consuming client applications.

This time I want to show how you can generate such an access token in a shell like bash or zsh.

Credentials

In the first step we need 3 things:

  • URL of OAuth2 endpoint
  • client ID
  • client secret

A good practise is to load them from environment variables:

#!/bin/bash

# URL of OAuth2 endpoint
# from TGF_OAUTH_URL environment variable
oauth_url="$TGF_OAUTH_URL"

# client credentials
# from TGF_CLIENT_ID and TGF_CLIENT_SECRET environment variables
client_id="$TGF_CLIENT_ID"
client_secret="$TGF_CLIENT_SECRET"

# ...

Do the request

We can make the first request using wget, which is typically installed by default in most Linux/UNIX distributions:

# ...

# get access token
# by calling endpoint in `oauth_url`
response=$(wget -qO- --post-data "grant_type=client_credentials&client_id=$client_id&client_secret=$client_secret" $oauth_url)

# ...

Extract the access token

Usually the response is a JSON containing an object with access_token, that contains the JWT.

A very good tool to query over JSON objects and extract data from it is jq:

# ...

# extract access token from JSON response
access_token=$(echo "$response" | jq -r '.access_token')

# ...

Finally we work with this access_token in the upcoming requests:

# ...

wget --header="Authorization: Bearer $access_token" "https://api.example.com/users"

# ...

Conclusion

You see, bash in combination with the right tools is very powerful.

A sample script can be found as a Gist on GitHub.

Have fun while trying it out! 🎉