How to implement two-factor authentication (2FA) in a golang app
Oct 16, 2025 am 11:18 AMGenerate a unique TOTP secret key per user using the pquerna/otp library and store it securely. 2. Create a QR code from the key URI for users to scan with authenticator apps like Google Authenticator. 3. During login, after password verification, prompt for the 6-digit TOTP code and validate it using totp.Validate(). 4. Maintain 2FA state in the user model, including secret storage, enabled status, and optional recovery codes for account access backup.
To implement two-factor authentication (2FA) in a Go (Golang) application, you typically use Time-Based One-Time Passwords (TOTP) following the RFC 6238 standard. This method integrates well with authenticator apps like Google Authenticator, Authy, or Microsoft Authenticator. Below is a clear guide on how to set up 2FA in your Go backend.
1. Generate a TOTP Secret Key
Each user needs a unique secret key for 2FA. This key is used to generate and verify one-time codes.
You can use the pquerna/otp library, which supports TOTP and HOTP. Install it via:
go get github.com/pquerna/otp go get github.com/pquerna/otp/totpGenerate a secret:
import "github.com/pquerna/otp/totp"key, err := totp.Generate(totp.GenerateOpts{
??Issuer: "your-app-name",
??AccountName: "user@example.com",
})
if err != nil {
??// handle error
}
secret := key.Secret() // Store this in your database
2. Display QR Code for Setup
Users need to scan a QR code with their authenticator app. The QR code contains a URI generated from the TOTP key.
The same library provides a way to get the QR code URL:
qrCode, err := totp.Generate(totp.GenerateOpts{??Issuer: "your-app-name",
??AccountName: "user@example.com",
})
if err != nil {
??// handle error
}
// Use qrCode.URL() to generate a QR code image
// You can use a QR code library like "github.com/skip2/go-qrcode" to render it
In your frontend (or email), display the QR code using the URL so the user can scan it.
3. Verify the 2FA Code
When the user logs in, after entering their password, prompt them for the 6-digit code from their app.
Verify it using:
valid := totp.Validate(userInput, secret)if valid {
??// 2FA successful
} else {
??// invalid code
}
The Validate function checks against the current time window (default 30 seconds). It allows some clock drift if needed by adjusting options.
4. Store and Manage 2FA State
In your user model, store:
- 2FA secret (encrypted at rest)
- Whether 2FA is enabled
- Recovery codes (optional but recommended)
During login flow:
- Authenticate username/password
- If 2FA is enabled, require TOTP code
- Call totp.Validate()
- Allow access only if both steps pass
Consider allowing recovery codes in case users lose their device.
Basically, that’s how you add secure 2FA to a Go app. Use TOTP, generate a secret per user, show a QR code, and validate input codes on login. Keep secrets safe and offer recovery options.
The above is the detailed content of How to implement two-factor authentication (2FA) in a golang app. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

struct{} is a fieldless structure in Go, which occupies zero bytes and is often used in scenarios where data is not required. It is used as a signal in the channel, such as goroutine synchronization; 2. Used as a collection of value types of maps to achieve key existence checks in efficient memory; 3. Definable stateless method receivers, suitable for dependency injection or organization functions. This type is widely used to express control flow and clear intentions.

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

GracefulshutdownsinGoapplicationsareessentialforreliability,achievedbyinterceptingOSsignalslikeSIGINTandSIGTERMusingtheos/signalpackagetoinitiateshutdownprocedures,thenstoppingHTTPserversgracefullywithhttp.Server’sShutdown()methodtoallowactiverequest

MiddlewareinGowebserversarefunctionsthatinterceptHTTPrequestsbeforetheyreachthehandler,enablingreusablecross-cuttingfunctionality;theyworkbywrappinghandlerstoaddpre-andpost-processinglogicsuchaslogging,authentication,CORS,orerrorrecovery,andcanbechai

CGOenablesGotocallCcode,allowingintegrationwithClibrarieslikeOpenSSL,accesstolow-levelsystemAPIs,andperformanceoptimization;itrequiresimporting"C"withCheadersincomments,usesC.function()syntax,anddemandscarefulmemorymanagement.However,CGOinc

Implements JSON serialization and deserialization of customizable Go structures for MarshalJSON and UnmarshalJSON, suitable for handling non-standard formats or compatible with old data. 2. Control the output structure through MarshalJSON, such as converting field formats; 3. Parsing special format data through UnmarshalJSON, such as custom dates; 4. Pay attention to avoid infinite loops caused by recursive calls, and use type alias to bypass custom methods.

TheflagpackageinGoparsescommand-lineargumentsbydefiningflagslikestring,int,orboolusingflag.StringVar,flag.IntVar,etc.,suchasflag.StringVar(&host,"host","localhost","serveraddress");afterdeclaringflags,callflag.Parse(

GenericsinGoenabletype-safe,reusablefunctionsanddatastructures.IntroducedinGo1.18,theyreducecodeduplicationbyallowingfunctionslikefuncMax[Tcomparable](a,bT)Ttoworkacrossmultipletypeswhileenforcingconstraints.Typeparametersinsquarebrackets,suchas[Tcom
