Golang 2 Factor Authentication

John Stupka
2 min readMar 4, 2021

--

Photo by melissa mjoen on Unsplash

To create an effective access pattern using 2 Factor Authentication (2FA), you will need to combine two login methods. One of those being basic authentication, and the one we’re going to use for this example One Time Password (OTP).

To start we’ll create a very simple API, with a static set of credentials and an API endpoint that we can login from.

Basic Authentication example

The above example creates a simple http server on http://localhost:8080/, with one endpoint called “/login” for you. There are two default values for logging in, the username and password at the top of the file and there is a internal method to break up the username and password from the request for us to use.

$ curl -v -u John:IamNotACat http://localhost:8080/login

Using the above command, test your service and ensure you have access to the server.

Using the example credentials and curl command, you can see 202 Accepted Success

This completes the first step of the example, a simple login process using basic authentication. The next step in the process will be setting up a OTP access code for the login process. For this example we’ll be using the library here: https://github.com/pquerna/otp

$ go get -u github.com/pquerna/otp

The above command will include the necessary library for creating a OTP access QR code for authenticating to the server.

Using the above OTP example code, you can access the endpoint at http://localhost:8080/QrCode which should bring you to something like this:

Example of using QrCode endpoint to get a QrCode in the browser

Using a OTP authentication app for your phone, scan the produced QR code. This should produce a time based access code you will use to access the http://localhost:8080/login endpoint.

curl -v -u John:IamNotACat localhost:8080/login --data '{"OTP":"ACCESS_CODE"}'

Using the access code from your authentication phone app and the basic credentials we defined earlier, you can now login with the endpoint.

Curl command using the OTP Access code to login

If you are interested in the source code for this, you can find it here:
https://github.com/hunter32292/2fa-example

I’m trying to add content with more coding examples in the future, if you like this change please let me know!

--

--

John Stupka
John Stupka

Written by John Stupka

Coffee Drinker, Chief Engineer of Dancing at Desk, Foodie, HyperText Transfer Operator, Overly energetic and active! 💻 ☕

No responses yet