Sample implementation of golang HTTP captcha

Time:2021-5-6

Captcha is the abbreviation of “completely automated Public Turing test to tell computers and humans apart”. It is a kind of public automatic program to distinguish whether a user is a computer or a human. Can prevent: malicious password cracking, ticket swiping, Forum irrigation, effectively prevent a hacker to a specific registered user with a specific program brute force cracking way for continuous landing attempts, in fact, using the verification code is now a popular way for many websites, we use a relatively simple way to achieve this function. This problem can be generated and judged by computer, but only human can solve it. Because computers can’t answer captcha’s questions, the user who answers the questions can be considered human.

Working mechanism of traditional website captcha

  • The client requests the server to get the captcha image
  • The server generates a random string (captcha value) to write to the session, and writes the captcha value to the picture and returns it to the client
  • The client input the string on the picture and submit it to the server for verification
  • The server compares whether the string value submitted by the client matches the session. If it matches, it passes the verification

Since the value of the verification code generated by the server is not returned to the client from the beginning to the end, the client can only recognize the verification code string from the picture, so as to ensure the human-machine verification logic.

HTTP verification code of go

thinking

The HTTP server of go language does not support session by default, so the verification code value needs to be stored in a different way. The following is the logic of not using session

  • The client requests the server to obtain the verification code ID
  • The server generates the verification code ID, generates the verification code value, records the mapping relationship between ID and value to memory or cache, and returns the ID to the client
  • The client requests the server to obtain the captcha image according to the returned ID
  • The server obtains the verification code ID, takes the verification code value from the memory or cache, writes the value to the image and returns the image to the client
  • The client submits the verification code ID (obtained in step 1) and the verification code value to the server for verification
  • The server obtains the verification code ID, takes out the verification code value from the memory or cache, and compares it with the verification code value submitted by the client

Examples

Install captcha dependency


github.com/dchest/captcha

code implementation

package main
  
  import (
    "fmt"
    "github.com/dchest/captcha"
    "log"
    "net/http"
  )
  
  func main() {
    //Get verification code ID
    http.HandleFunc("/captcha/generate", func(w http.ResponseWriter, r *http.Request) {
      id := captcha.NewLen(6)
      if _, err := fmt.Fprint(w, id); err != nil {
        log.Println("generate captcha error", err)
      }
    })
    //Get captcha image
    http.HandleFunc("/captcha/image", func(w http.ResponseWriter, r *http.Request) {
      id := r.URL.Query().Get("id")
      if id == "" {
        http.Error(w, "Bad Request", http.StatusBadRequest)
        return
      }
      w.Header().Set("Content-Type", "image/png")
      if err := captcha.WriteImage(w, id, 120, 80); err != nil {
        log.Println("show captcha error", err)
      }
    })
    //Business processing
    http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
      if err := r.ParseForm(); err != nil {
        log.Println("parseForm error", err)
        http.Error(w, "Internal Error", http.StatusInternalServerError)
        return
      }
      //Get verification code ID 和验证码值
      id := r.FormValue("id")
      value := r.FormValue("value")
      //Compare the submitted captcha value with the one in memory
      if captcha.VerifyString(id, value) {
        fmt.Fprint(w, "ok")
      } else {
        fmt.Fprint(w, "mismatch")
      }
    })
    log.Fatal(http.ListenAndServe(":8080", nil))
  }

function

  • Access / captcha / generate to get the captcha ID
  • Access / captcha / image? Id = captcha ID
  • Visit / login and enter the verification code ID of the first step and the verification code value of the second step to view the verification results

Project address

https://github.com/xialeistudio/go-http-captcha-example

Here is the article about the implementation of golang HTTP captcha. For more information about golang HTTP captcha, please search previous articles of developer or continue to browse the following articles. I hope you can support developer more in the future!