Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。

验证码字符

如果考虑用户输入体验,一般只用数字验证码,考虑到安全,防识别、碰撞,要生成6个数字的验证码,并且使字符弯曲变形、变色、加干扰。如下图效果:

验证码 captcha

captcha

github 上的 github.com/dchest/captcha 库已经做得很好,下面是参照官方的例子做一下改动。

package main

import (
    "fmt"
    "github.com/dchest/captcha"
    "io"
    "log"
    "net/http"
    "text/template"
)

var formTemplate = template.Must(template.New("example").Parse(formTemplateSrc))

func showFormHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }
    d := struct {
        CaptchaId string
    }{
        captcha.New(),
    }
    if err := formTemplate.Execute(w, &d); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func processFormHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
        io.WriteString(w, "Wrong captcha solution! No robots allowed!\n")
    } else {
        io.WriteString(w, "Great job, human! You solved the captcha.\n")
    }
    io.WriteString(w, "<br><a href='/'>Try another one</a>")
}

func main() {
    http.HandleFunc("/", showFormHandler)
    http.HandleFunc("/process", processFormHandler)
    http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
    fmt.Println("Server is at localhost:8666")
    if err := http.ListenAndServe("localhost:8666", nil); err != nil {
        log.Fatal(err)
    }
}

const formTemplateSrc = `<!doctype html>
<head><title>Captcha Example</title></head>
<body>
<script>
function setSrcQuery(e, q) {
    var src  = e.src;
    var p = src.indexOf('?');
    if (p >= 0) {
        src = src.substr(0, p);
    }
    e.src = src + "?" + q
}

function reload() {
    setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
    return false;
}
</script>
<form action="/process" method=post>
<p>Type the numbers you see in the picture below:</p>
<p><img id=image src="/captcha/{{.CaptchaId}}.png" alt="Captcha image"></p>
<a href="#" onclick="reload()">Reload</a>

<input type=hidden name=captchaId value="{{.CaptchaId}}"><br>
<input name=captchaSolution>
<input type=submit value=Submit>
</form>
`

注意事项

当验证以后 CaptchaId 会销毁,如果验证码验证不对,需要重新生成CaptchaId并把它传给前端显示。

captcha 项目地址 https://github.com/dchest/captcha 7

Relative Articles
本文网址: https://www.golangnote.com/topic/228.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。