Authentication in Golang
By: David Abimbola
Tags: Postgres, Golang, Go, API, Authentication

Full source code available available on github

📄 Table of contents

Why Go ?

Dependency Management in Go

Prerequisite

Dependencies

Database connection

Structure

User Registration

User login

Authentication Middleware

Conclusion

Why Go?

Go is a programming language developed by Google for building modern software.It is an excellent choice in building fast and scalable apps.It compiles down to native code and it does so very fast usually in just a few seconds.It is a statically typed language and well compiled after the syntax of tradition C .

Some key features include:

It is written in a self documenting way.The documentation is very much concise and precise.

Great support for concurrency.

Extensive standard library.

Dependency Management in Go

In managing dependency in Go, DEP is an excellent choice just like NPM for Nodejs. When creating a Go project , it should be inside $GOPATH.If you haven’t configured your GOPATH follow this link. We’ll create our project with dep using this command

$ dep init

This creates a go project for you.It creates the below files for you

Gopkg.toml

Gopkg.lock

vendor/

To install dependencies with dep we use this command

where github.com/gorilla/mux is the name of the dependency.

Prerequisite

It is necessary to have the below set up before going further in this tutorial:

Dependencies

The following package are used:

Gorilla mux (For routing )

Gorm (ORM library for Golang)

JWT-GO (Go implementation of JWT)

GODOTENV (Load environmental variables)

We’ll be installing this package using Dep

Running the above command in the terminal will install the dependencies listed.

Database connection

We’ll be using Postgres as our database so its necessary you have Postgres installed on your machine.We need to define our environmental variables by creating a .env file like so.

databaseName = expense databasePassword = david databaseUser = david databaseType = postgres databaseHost = localhost databasePort = 5434 PORT = 8080

We can now write our function to connect to our database.It is important we first create our database manually before going forward.To do that we need to head to our terminal and run the command

psql postgres

then

CREATE DATABASE expense;

where expense is the database name.Now that we’ve created the database we can now write our Go function that connects to the database.

Line 33 above opens the connection given the Database URI define in line 30.

Structure

User registration( Setting up routes and database)

User login

Route protection

User Registration

The first thing we need to do here is to define the user model.We’ll be embedding gorm.Model from Gorm in our model definition.

We’ll be defining our user model like so:

now that we’ve our user model defined, let’s write the controller to create a new user in our database

The CreateUser function define above does the following:

1. Reads the content of the request body. 2. Cast the request body content into our user struct. 3. Encrypt the user password before saving. 4. Save the user information. 5. Return a response containing the new user information.

User Login

After creating the user, we need to test if the user was successfully created and return a token if the information sent is the same with the one present in our database.

The Login function defined above does the following:

1. Read the content of the request body. 2. Cast the request body content into our user struct. If there is an error when casting,Return an error response . 3. Pass the email and password inside the FindOne function and invoke it. 4 . Check if the email provided is present in our database. If the email is not present return an error response. 5. Check if the password is the same with the one provided if the password is not the same return an error response. 6. Create a token for the user 7. Attach the token to the user object and send the response

Authentication Middleware

Middlewares are functions that runs after a request is received ,process the request and performs necessary action before returning a response.

In Golang, they are functions that takes in a net/http.Handler and returns a net/http.Handler.An example of a simple middleware is defined below:

We’ll create a simple middleware that checks it token is passed in the request headers,validate and decode the token.

From the above, we define our route.The first four route defined doesn’t need authentication.The remaining routes needs authentication.At line 13 from the above we are setting the route to use the authentication middleware we define above.

Conclusion

We have learnt how to:

How to manage dependencies in Go.

How to use Dep.

How to create middlewares in Go.

How to protect routes.

You can find complete source code on Github here. Feel free to leave your comments, questions and suggestion.Thank you for reading 😃 .