JSON Web Tokens: Authenticating your API
·
565 words
·
3 minutes read
There are of course many different ways to build authentication into APIs these days - JSON web tokens being just one of them. JSON Web Tokens (JWT) have an inherent advantage over other methods, like Basic Authentication, by working as a token system instead of sending the username and password with every request. To learn more about it, head over to the introduction on jwt.io before we dive straight into it.
Below is an example of JWT in action. There are two main parts: the providing of a username and password to acquire a token; and the checking of that token on a request.
We use two libraries in this example, a JWT implementation in Go and a way of using this as middleware.
Finally, before using this code you will need to change the APP_KEY
constant into a secret (which would ideally be stored outside of the code-base) and improve the username/password checking in the TokenHandler
to check for more than just a myusername
/mypassword
combination.
|
|
We show above an example flow, first getting a token then using that token when calling an endpoint. These are the commands we used:
|
|
|
|