This is an example of Using JWT Authorization via golang web framework iris.
Iris is a good but not nice Golang web framework, it has most features than all exists Golang web framework , but the main developer looks like having some ...
I found the documention of Iris is not friendly for developers, but Golang doc is enough for Gophers, and the examples almost worse.
Let's inspect an example of Iris:
1 | https://github.com/iris-contrib/middleware/blob/master/jwt/_example/main.go |
You will get nothing but an error message when you run it, why? may only someone spending much time to correct it will know why.
The following is a "better" example of it, cause it works at least :
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | package main import ( //"encoding/json" "fmt" "github.com/dgrijalva/jwt-go" jwtmiddleware "github.com/iris-contrib/middleware/jwt" "github.com/kataras/iris" "github.com/mitchellh/mapstructure" "log" ) const jwtAuthSecretKey = "suifengtec" type jwtUser struct { Username string `json:"username"` Password string `json:"password"` } //数据有效性验证的mock 方法 func (user *jwtUser) isValid() bool { b := true return b } type jwtToken struct { Token string `json:"token"` } type jwtResponse struct { Success bool `json:"success"` Message string `json:"message"` } func createTokenHandler(ctx iris.Context) { //var user jwtUser user := new(jwtUser) if err := ctx.ReadJSON(user); err != nil { panic(err.Error()) } else { /* user=> &main.jwtUser{Username:"admin", Password:"admin"} */ //fmt.Printf("user=> %#v", user) //ctx.Write([]byte("ok")) } //_ = json.NewDecoder(req.Body).Decode(&user) token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "username": user.Username, "password": user.Password, }) tokenString, error := token.SignedString([]byte(jwtAuthSecretKey)) if error != nil { fmt.Println(error) } ctx.Header("Content-Type", "application/json") ctx.JSON(jwtToken{Token: tokenString}) } // GET 操作 func testHandler(ctx iris.Context) { ctx.Header("Content-Type", "application/json") //从哪里获取token,可选,最佳是从header //tokenRaw := ctx.PostValue("token") //tokenRaw := ctx.URLParam("token") //jwtmiddleware.FromAuthHeader(ctx) tokenRaw, err := jwtmiddleware.FromAuthHeader(ctx) if err != nil { log.Fatal(err) } token, err := jwt.Parse(tokenRaw, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("There was an error") } return []byte(jwtAuthSecretKey), nil }) if err != nil { log.Fatal(err) } if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { var user jwtUser mapstructure.Decode(claims, &user) ctx.JSON(user) } else { ctx.JSON(jwtResponse{Message: "Invalid authorization token"}) } } // 比 testHandler 添加个数据的有效性验证(通常是从持久化存储中验证用户数据是否有效)层 func validateHandler(ctx iris.Context) { ctx.Header("Content-Type", "application/json") tokenRaw, err := jwtmiddleware.FromAuthHeader(ctx) if err != nil { log.Fatal(err) } token, err := jwt.Parse(tokenRaw, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("WTF?") } return []byte(jwtAuthSecretKey), nil }) if err != nil { log.Fatal(err) } if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { //var user jwtUser user := new(jwtUser) mapstructure.Decode(claims, &user) //数据有效性验证的mock 方法 if user.isValid() { ctx.JSON(jwtResponse{Success: true, Message: "success"}) } else { ctx.JSON(jwtResponse{Message: "Invalid request."}) } } else { ctx.JSON(jwtResponse{Message: "Invalid token."}) } } func main() { app := iris.New() // New constructs a new Secure instance with supplied options. //*Middleware jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{ // The function that will return the Key to validate the JWT. // It can be either a shared secret or a public key. // Default value: nil //jwt.Keyfunc ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { return []byte(jwtAuthSecretKey), nil }, // The name of the property in the request where the user (&token) information // from the JWT will be stored. // Default value: "jwt" ContextKey: "token", // Debug flag turns on debugging output // Default: false Debug: true, SigningMethod: jwt.SigningMethodHS256, }) // Serve the middleware's action app.Use(jwtHandler.Serve) /* POST http://localhost:3001/token RAW: { "username": "admin", "password": "admin" } RESPONSE: { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6ImFkbWluIiwidXNlcm5hbWUiOiJhZG1pbiJ9.lfBO7TrUSpBJJwypVhoaqMR6w6esLINlNEY2Yyz4JOI" } */ app.Post("/token", createTokenHandler) /* http://localhost:3001/test/ 带上header */ app.Get("/test", testHandler) /* http://localhost:3001/validate/ 带上header 正确的响应 { "success": true, "message": "success" } */ app.Get("/validate", validateHandler) app.Run(iris.Addr(":3001")) } |
Generate a token by a given username and password pair:
test JWT token:
validating JWT token: