Golang 2 Factor Authentication

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.

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

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.

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!

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
John Stupka

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