GolangNote

Golang笔记

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

Permalink

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

验证码字符

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

验证码 captcha

captcha

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

Go: 图片验证码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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

本文网址: https://golangnote.com/topic/228.html 转摘请注明来源

Related articles

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

Write a Comment to "Golang 生成防识别的图片验证码"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms