Last active
March 25, 2020 09:23
-
-
Save codenoid/40c9b0f0315d76c276d2383d9f1ab498 to your computer and use it in GitHub Desktop.
Golang Simple Token-Auth Example (non RFC compliant)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "log" | |
| "net/http" | |
| "time" | |
| ) | |
| import ( | |
| "github.com/julienschmidt/httprouter" | |
| "github.com/patrickmn/go-cache" | |
| "github.com/thanhpk/randstr" | |
| ) | |
| var ( | |
| // Create a cache with a default expiration time of 5 minutes, and which | |
| // purges expired items every 10 minutes | |
| memory = cache.New(5*time.Minute, 10*time.Minute) | |
| ) | |
| func GetToken(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { | |
| w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) | |
| username, password, authOK := r.BasicAuth() | |
| if authOK == false { | |
| http.Error(w, "Not authorized", 401) | |
| return | |
| } | |
| if username != "username" || password != "password" { | |
| http.Error(w, "Not authorized", 401) | |
| return | |
| } | |
| rand_uuid := randstr.Hex(16) | |
| // UUID is valid until cache.DefaultExpiration | |
| memory.Set(rand_uuid, "", cache.DefaultExpiration) | |
| token := map[string]string{ | |
| "token": rand_uuid, | |
| } | |
| uj, _ := json.Marshal(token) | |
| w.Header().Set("Content-Type", "application/json") | |
| w.WriteHeader(200) | |
| fmt.Fprintln(w, string(uj)) | |
| } | |
| func CheckToken(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { | |
| w.Header().Set("Content-Type", "text/html") | |
| token := r.FormValue("token") | |
| message := "" | |
| if token != "" { | |
| _, valid := memory.Get(token) | |
| if valid { | |
| w.WriteHeader(200) | |
| message = fmt.Sprintf("%v is a Valid token !", token) | |
| fmt.Fprintln(w, message) | |
| return | |
| } | |
| } | |
| message = fmt.Sprintf("%v is not a Valid token !", token) | |
| w.WriteHeader(401) | |
| fmt.Fprintln(w, message) | |
| } | |
| func main() { | |
| router := httprouter.New() | |
| router.POST("/check", CheckToken) | |
| router.GET("/token", GetToken) | |
| log.Fatal(http.ListenAndServe("127.0.0.1:4005", router)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment