Golang:使用Base64Captcha生成数字字母验证码实现安全校验

Base64Captcha可以在服务端生成验证码,以base64的格式返回

为了能看到生成的base64验证码图片,我们借助gin

bash 复制代码
go get -u github.com/mojocn/base64Captcha
go get -u github.com/gin-gonic/gin

文档的示例看起来很复杂,下面,通过简单的一个小实例,来展示Base64Captcha的基本使用

项目示例

目录结构

bash 复制代码
main.go
captcha_util
	/captcha_util.go
templates
	/index.html

先写一个工具类,将base64Captcha进行简单的封装,实现主要的功能:生成验证码验证验证码

go 复制代码
package captcha_util

import (
	"github.com/mojocn/base64Captcha"
)

// 验证码工具类
type StringCaptcha struct {
	captcha *base64Captcha.Captcha
}

// 创建验证码
func NewCaptcha() *StringCaptcha {
	// store
	store := base64Captcha.DefaultMemStore

	// 包含数字和字母的字符集
	source := "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"

	// driver
	driver := base64Captcha.NewDriverString(
		80,     // height int
		240,    // width int
		6,      // noiseCount int
		1,      // showLineOptions int
		4,      // length int
		source, // source string
		nil,    // bgColor *color.RGBA
		nil,    // fontsStorage FontsStorage
		nil,    // fonts []string
	)

	captcha := base64Captcha.NewCaptcha(driver, store)
	return &StringCaptcha{
		captcha: captcha,
	}
}

// 生成验证码
func (stringCaptcha *StringCaptcha) Generate() (string, string, string) {
	id, b64s, answer, _ := stringCaptcha.captcha.Generate()
	return id, b64s, answer
}

// 验证验证码
func (stringCaptcha *StringCaptcha) Verify(id string, answer string) bool {
	return stringCaptcha.captcha.Verify(id, answer, true)
}

通过gin的两个路由,分别输出验证码验证验证码

go 复制代码
package main

import (
	"demo/captcha_util"
	"fmt"
	"html/template"
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	app := gin.Default()

	// 加载模板文件
	app.LoadHTMLGlob("templates/*")

	// 验证码
	stringCaptcha := captcha_util.NewCaptcha()

	// 生成验证码
	app.GET("/generate", func(ctx *gin.Context) {
		id, b64s, answer := stringCaptcha.Generate()
		fmt.Println(answer)

		ctx.HTML(http.StatusOK, "index.html", gin.H{
			"captchaId": id,
			"b64s":      template.URL(b64s),
			"answer":    answer,
		})
	})

	// 验证
	app.POST("/verify", func(ctx *gin.Context) {
		answer := ctx.PostForm("answer")
		captchaId := ctx.PostForm("captchaId")

		result := stringCaptcha.Verify(captchaId, answer)

		ctx.JSON(http.StatusOK, gin.H{
			"captchaId": captchaId,
			"answer":    answer,
			"result":    result,
		})
	})

	// 监听并在 http://127.0.0.1:8080 上启动服务
	app.Run()
}

index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
</head>
<body>
    <img src="{{.b64s}}">

    <form action="/verify" method="post">
        <input type="text" name="captchaId" value="{{.captchaId}}" hidden>
        <input type="text" name="answer" value="">
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>

生成验证码页面,为了便于显示,直接用模板渲染的方式处理,也可已改为返回接口数据

http://localhost:8080/generate

提交验证码后返回验证结果

http://localhost:8080/verify

参考文章

相关推荐
好开心啊没烦恼1 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20202 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
Python×CATIA工业智造5 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
我叫小白菜6 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
运维开发王义杰6 小时前
金融安全生命线:用AWS EventBridge和CloudTrail构建主动式入侵检测系统
安全·金融·aws
狐凄6 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
weixin_446122467 小时前
JAVA内存区域划分
java·开发语言·redis
悦悦子a啊7 小时前
Python之--基本知识
开发语言·前端·python
QuantumStack8 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
安全系统学习8 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss