Learn how to protect API endpoints with access and refresh tokens using the third-party jwt-go library.
This post belongs to the following series:
- How to Build an API Server in Go - Part 1: Basic Server
- How to Build an API Server in Go - Part 2: Simple Database
- How to Build an API Server in Go - Part 3: Postgres Database
- How to Build an API Server in Go - Part 4: Access Control
Authentication
Just as a reminder this is part 4 of the series, you’ll need to finish part 3 before continuing.
Structure
📦mulberry-server
│ 📄README.md
│ 📄Makefile
│
└───📁cmd
│ |
| └───📁serve
| 📄main.go
│
└───📁internal
| │
| └───📁controllers
| │ 📄controller.go
| │ 📄middleware.go
| │ 📄tsd.go
| │ 📄user.go
| │ 📄version.go
| |
| └───📁repositories
| 📄tsd.go
| 📄user.go
|
└───📁pkg
|
└───📁db
| 📄db.go
|
└───📁models
| 📄tsd.go
| 📄user.go
|
└───📁utils
📄jwt.go
📄password.go
models package
user.go
|
|
utils package
jwt.go
|
|
controllers package
middleware.go
|
|
controller.go
|
|
user.go
|
|
tsd.go
|
|
serve package
main.go
|
|
Testing
Starting the Server
We are going to use environment variables to load configuration settings for our application.
export MULBERRY_DB_HOST=localhost
export MULBERRY_DB_PORT=5432
export MULBERRY_DB_USER=golang
export MULBERRY_DB_PASSWORD=123password
export MULBERRY_DB_NAME=mulberry_db
export MULBERRY_APP_SIGNING_KEY=PLEASE_REPLACE_ME
And now you can run the code:
go run cmd/serve/main.go
In another terminal run the following code to make a login call:
bmika@MACMINI-AFA2131 mulberry-server % http post 127.0.0.1:5000/api/v1/login email="fherbert@dune.com" password="the-spice-must-flow"
The return should look as follows:
HTTP/1.1 200 OK
Content-Length: 385
Content-Type: application/json
Date: Mon, 01 Feb 2021 04:27:46 GMT
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTIxNTcyNjYsInVzZXJfdXVpZCI6IjlkZDJjYzBhLTkzNGQtNDc4OC04MzA0LTFlMGI4MmQ5YjZlNiJ9.ZKe5DargCrHZcAQQ71M46uUr0TWk9UYkiURijaKBABA",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTI0MTI4NjYsInVzZXJfdXVpZCI6IjlkZDJjYzBhLTkzNGQtNDc4OC04MzA0LTFlMGI4MmQ5YjZlNiJ9.odXNQd1hm3cLPI9_e2jfjYXjgjf7wfxQ8hCx3-qqZYY"
}
Please save the output the “access_token” so you can write in your console.
export MULBERRY_API_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTIxNTcyNjYsInVzZXJfdXVpZCI6IjlkZDJjYzBhLTkzNGQtNDc4OC04MzA0LTFlMGI4MmQ5YjZlNiJ9.ZKe5DargCrHZcAQQ71M46uUr0TWk9UYkiURijaKBABA"
Next run the following call to a protected API:
http get 127.0.0.1:5000/api/v1/time-series-data Authorization:"Bearer $MULBERRY_API_TOKEN"
And your result should look like this:
HTTP/1.1 200 OK
Content-Length: 175
Content-Type: application/json
Date: Sun, 31 Jan 2021 22:57:40 GMT
[
{
"instrument_uuid": "lalala",
"timestamp": "2021-01-30T10:20:10Z",
"user_uuid": "9dd2cc0a-934d-4788-8304-1e0b82d9b6e6",
"uuid": "923148e4-5dd9-4ec7-bf04-4a50f880c7db",
"value": 123
}
]