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

参考文章

相关推荐
白帽黑客沐瑶3 小时前
【网络安全就业】信息安全专业的就业前景(非常详细)零基础入门到精通,收藏这篇就够了
网络·安全·web安全·计算机·程序员·编程·网络安全就业
侃侃_天下3 小时前
最终的信号类
开发语言·c++·算法
深盾安全3 小时前
符号执行技术实践-求解程序密码
安全
echoarts3 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix4 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
贾维思基4 小时前
被监管警告后,我连夜给系统上了“双保险”!
安全
每天回答3个问题4 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说4 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔5 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
00后程序员张5 小时前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview