亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1. Generate a TOTP Secret Key
2. Display QR Code for Setup
3. Verify the 2FA Code
4. Store and Manage 2FA State
Home Backend Development Golang How to implement two-factor authentication (2FA) in a golang app

How to implement two-factor authentication (2FA) in a golang app

Oct 16, 2025 am 11:18 AM
golang Two-factor authentication

Generate 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.

How to implement two-factor authentication (2FA) in a golang app

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/totp

Generate 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:

  1. Authenticate username/password
  2. If 2FA is enabled, require TOTP code
  3. Call totp.Validate()
  4. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

What is the empty struct struct{} used for in Golang What is the empty struct struct{} used for in Golang Sep 18, 2025 am 05:47 AM

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.

How do you read and write files in Golang? How do you read and write files in Golang? Sep 21, 2025 am 01:59 AM

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

How do you handle graceful shutdowns in a Golang application? How do you handle graceful shutdowns in a Golang application? Sep 21, 2025 am 02:30 AM

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

What are middleware in the context of Golang web servers? What are middleware in the context of Golang web servers? Sep 16, 2025 am 02:16 AM

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

What is CGO and when to use it in Golang What is CGO and when to use it in Golang Sep 21, 2025 am 02:55 AM

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

How to create a custom marshaller/unmarshaller for JSON in Golang How to create a custom marshaller/unmarshaller for JSON in Golang Sep 19, 2025 am 12:01 AM

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.

How to use the flag package in Golang How to use the flag package in Golang Sep 18, 2025 am 05:23 AM

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

How to use generics in Golang How to use generics in Golang Sep 19, 2025 am 05:29 AM

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

See all articles