title: JWT url: /cookbook/jwt menu: side: identifier: jwt-recipe parent: cookbook

  1. weight: 14

JWT

  • JWT 使用 HS256 算法认证。
  • JWT 从 Authorization 请求头取出数据。

服务端(使用 map)

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "time"
  5. jwt "github.com/dgrijalva/jwt-go"
  6. "github.com/labstack/echo"
  7. "github.com/labstack/echo/middleware"
  8. )
  9. func login(c echo.Context) error {
  10. username := c.FormValue("username")
  11. password := c.FormValue("password")
  12. if username == "jon" && password == "shhh!" {
  13. // Create token
  14. token := jwt.New(jwt.SigningMethodHS256)
  15. // Set claims
  16. claims := token.Claims.(jwt.MapClaims)
  17. claims["name"] = "Jon Snow"
  18. claims["admin"] = true
  19. claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
  20. // Generate encoded token and send it as response.
  21. t, err := token.SignedString([]byte("secret"))
  22. if err != nil {
  23. return err
  24. }
  25. return c.JSON(http.StatusOK, map[string]string{
  26. "token": t,
  27. })
  28. }
  29. return echo.ErrUnauthorized
  30. }
  31. func accessible(c echo.Context) error {
  32. return c.String(http.StatusOK, "Accessible")
  33. }
  34. func restricted(c echo.Context) error {
  35. user := c.Get("user").(*jwt.Token)
  36. claims := user.Claims.(jwt.MapClaims)
  37. name := claims["name"].(string)
  38. return c.String(http.StatusOK, "Welcome "+name+"!")
  39. }
  40. func main() {
  41. e := echo.New()
  42. // Middleware
  43. e.Use(middleware.Logger())
  44. e.Use(middleware.Recover())
  45. // Login route
  46. e.POST("/login", login)
  47. // Unauthenticated route
  48. e.GET("/", accessible)
  49. // Restricted group
  50. r := e.Group("/restricted")
  51. r.Use(middleware.JWT([]byte("secret")))
  52. r.GET("", restricted)
  53. e.Logger.Fatal(e.Start(":1323"))
  54. }

服务端(使用结构体)

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "time"
  5. jwt "github.com/dgrijalva/jwt-go"
  6. "github.com/labstack/echo"
  7. "github.com/labstack/echo/middleware"
  8. )
  9. // jwtCustomClaims are custom claims extending default ones.
  10. type jwtCustomClaims struct {
  11. Name string `json:"name"`
  12. Admin bool `json:"admin"`
  13. jwt.StandardClaims
  14. }
  15. func login(c echo.Context) error {
  16. username := c.FormValue("username")
  17. password := c.FormValue("password")
  18. if username == "jon" && password == "shhh!" {
  19. // Set custom claims
  20. claims := &jwtCustomClaims{
  21. "Jon Snow",
  22. true,
  23. jwt.StandardClaims{
  24. ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
  25. },
  26. }
  27. // Create token with claims
  28. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  29. // Generate encoded token and send it as response.
  30. t, err := token.SignedString([]byte("secret"))
  31. if err != nil {
  32. return err
  33. }
  34. return c.JSON(http.StatusOK, echo.Map{
  35. "token": t,
  36. })
  37. }
  38. return echo.ErrUnauthorized
  39. }
  40. func accessible(c echo.Context) error {
  41. return c.String(http.StatusOK, "Accessible")
  42. }
  43. func restricted(c echo.Context) error {
  44. user := c.Get("user").(*jwt.Token)
  45. claims := user.Claims.(*jwtCustomClaims)
  46. name := claims.Name
  47. return c.String(http.StatusOK, "Welcome "+name+"!")
  48. }
  49. func main() {
  50. e := echo.New()
  51. // Middleware
  52. e.Use(middleware.Logger())
  53. e.Use(middleware.Recover())
  54. // Login route
  55. e.POST("/login", login)
  56. // Unauthenticated route
  57. e.GET("/", accessible)
  58. // Restricted group
  59. r := e.Group("/restricted")
  60. // Configure middleware with the custom claims type
  61. config := middleware.JWTConfig{
  62. Claims: &jwtCustomClaims{},
  63. SigningKey: []byte("secret"),
  64. }
  65. r.Use(middleware.JWTWithConfig(config))
  66. r.GET("", restricted)
  67. e.Logger.Fatal(e.Start(":1323"))
  68. }

客户端

curl

登录

使用账号和密码登录获取 token。

  1. curl -X POST -d 'username=jon' -d 'password=shhh!' localhost:1323/login

返回

  1. {
  2. "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NjE5NTcxMzZ9.RB3arc4-OyzASAaUhC2W3ReWaXAt_z2Fd3BN4aWTgEY"
  3. }

请求

Authorization 请求头设置 token,发送请求获取资源。

  1. curl localhost:1323/restricted -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NjE5NTcxMzZ9.RB3arc4-OyzASAaUhC2W3ReWaXAt_z2Fd3BN4aWTgEY"

返回

  1. Welcome Jon Snow!