Implementing Two-Factor Authentication (2FA) with TOTP in Go

Two-Factor Authentication (2FA) is a security method that requires two forms of identification before granting access to a system. In this article, we will see how to implement a simple 2FA system using Time-based One-Time Password (TOTP) codes in Go.

Prerequisites

  • A configured Go environment
  • A TOTP library, such as github.com/pquerna/otp

1. Installing the OTP Library

To start, we need to install the library that handles TOTP:

go get github.com/pquerna/otp

2. Generating a TOTP Secret

Each user should have a unique secret that will be used to generate temporary codes. Here’s how to generate it:

package main

import (
    "fmt"
    "github.com/pquerna/otp/totp"
)

func main() {
    key, err := totp.Generate(totp.GenerateOpts{
        Issuer:      "ExampleApp",
        AccountName: "user@example.com",
    })
    if err != nil {
        panic(err)
    }

    fmt.Println("Secret:", key.Secret())
    fmt.Println("OTPAuth URL:", key.URL())
}

The key.URL() field can be converted into a QR code and scanned with an app like Google Authenticator or Authy.

3. Verifying OTP Codes

Once the user has configured the 2FA app, they can start entering the generated codes. We can verify them with:

package main

import (
    "fmt"
    "github.com/pquerna/otp/totp"
    "time"
)

func main() {
    secret := "ABCDEF1234567890" // replace with the user's secret
    code := "123456"             // code entered by the user

    valid := totp.Validate(code, secret)
    if valid {
        fmt.Println("Valid code")
    } else {
        fmt.Println("Invalid code")
    }
}

The totp.Validate function compares the entered code with the one generated at that moment, allowing for a small time window to compensate for potential clock differences.

4. Security and Best Practices

  • Store TOTP secrets securely, for example in an encrypted database.
  • Use HTTPS for all communications between client and server.
  • Never log secrets or OTP codes.

Conclusion

Implementing two-factor authentication in Go is relatively simple thanks to libraries like pquerna/otp. By adding this security measure, you better protect user access, reducing the risk of compromise even in case of password theft.

Back to top