golang实现接入Google应用Authenticator

首先安装OTP 库

go get github.com/pquerna/otp

安装完成之后可以用top库生成需要的Authenticator

dataMap := make(map[string]string)

// 生成一个随机的密钥
key, err2 := totp.Generate(totp.GenerateOpts{
	Issuer:      "xxx", 
	AccountName: "xxx",
})
//生成的信息可以存储到mysql 或者redis 里面方便下次验证

dataMap["SecretKey"] = key.Secret()   //生成的 密钥
dataMap["UrlKey"] = key.URL() //生成的二维码链接 ,可以通过链接进行二维码绑定到应用上


 // 验证 OTP 码   code 是用户输入的
    valid := totp.Validate(code, dataMap["SecretKey"])
    if valid {
        fmt.Println("OTP 验证通过")
    } else {
        fmt.Println("OTP 验证失败")
    }

也可以根据业务实现一次性的验证方式

大概步骤就是:

  1. 使用 totp.Generate 函数生成一个随机的密钥(key),可以指定发行者(Issuer)和账户名(AccountName)。
  2. 使用 totp.GenerateCode 函数根据密钥和当前时间生成 OTP 码。otp.CurrentTime() 函数用于获取当前时间。
    code, err := totp.GenerateCode(key.Secret(), otp.CurrentTime())
        if err != nil {
            fmt.Printf("Error generating code: %s\n", err)
            return
        }
  3. 打印生成的 OTP 码。
  4. 使用 totp.Validate 函数验证 OTP 码是否正确,传入 OTP 码和密钥进行验证。

更多玩法需要大家自己diy了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值