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

参考文章

相关推荐
想吃火锅10058 小时前
【leetcode】405.数字转换为十六进制数js
开发语言·javascript·ecmascript
HackTwoHub9 小时前
最新Nessus2026.6.8版本主机漏洞扫描/探测工具Windows/Linux
linux·运维·服务器·安全·web安全·网络安全·安全架构
专注VB编程开发20年9 小时前
AI 生成C# WinForm 窗体 = 目前就是垃圾
开发语言·人工智能·c#
cfm_29149 小时前
JVM GC垃圾回收初步了解
java·开发语言·jvm
~小先生~9 小时前
Python从入门到放弃(一)
开发语言·python
许彰午10 小时前
17_synchronized关键字深度解析
java·开发语言
z落落10 小时前
C# 泛型接口和泛型类+泛型约束
开发语言·c#
阿正的梦工坊10 小时前
【Rust】02-变量、不可变性与基础类型
开发语言·后端·rust
阿正的梦工坊10 小时前
【Rust】08-集合类型、字符串与迭代器入门
开发语言·rust·c#
FuckPatience10 小时前
C# 使用泛型协变将派生类类型替换为基类类型
开发语言·c#