Golang 2 Factor Authentication
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.
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.
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:
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.
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!