项目作者: appleboy

项目描述 :
JWT Middleware for Gin framework
高级语言: Go
项目地址: git://github.com/appleboy/gin-jwt.git
创建时间: 2016-03-17T03:18:36Z
项目社区:https://github.com/appleboy/gin-jwt

开源协议:MIT License

下载


JWT Middleware for Gin Framework

Run Tests
GitHub tag
GoDoc
Go Report Card
codecov
codebeat badge
Sourcegraph

This is a middleware for Gin framework.

It uses jwt-go to provide a jwt authentication middleware. It provides additional handler functions to provide the login api that will generate the token and an additional refresh handler that can be used to refresh tokens.

Security Issue

Simple HS256 JWT token brute force cracker. Effective only to crack JWT tokens with weak secrets. Recommendation: Use strong long secrets or RS256 tokens. See the jwt-cracker repository.

Usage

Download and install using go module:

  1. export GO111MODULE=on
  2. go get github.com/appleboy/gin-jwt/v2

Import it in your code:

  1. import "github.com/appleboy/gin-jwt/v2"

Download and install without using go module:

  1. go get github.com/appleboy/gin-jwt

Import it in your code:

  1. import "github.com/appleboy/gin-jwt"

Example

Please see the example file and you can use ExtractClaims to fetch user data.

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. "time"
  7. jwt "github.com/appleboy/gin-jwt/v2"
  8. "github.com/gin-gonic/gin"
  9. )
  10. type login struct {
  11. Username string `form:"username" json:"username" binding:"required"`
  12. Password string `form:"password" json:"password" binding:"required"`
  13. }
  14. var (
  15. identityKey = "id"
  16. port string
  17. )
  18. // User demo
  19. type User struct {
  20. UserName string
  21. FirstName string
  22. LastName string
  23. }
  24. func init() {
  25. port = os.Getenv("PORT")
  26. if port == "" {
  27. port = "8000"
  28. }
  29. }
  30. func main() {
  31. engine := gin.Default()
  32. // the jwt middleware
  33. authMiddleware, err := jwt.New(initParams())
  34. if err != nil {
  35. log.Fatal("JWT Error:" + err.Error())
  36. }
  37. // register middleware
  38. engine.Use(handlerMiddleware(authMiddleware))
  39. // register route
  40. registerRoute(engine, authMiddleware)
  41. // start http server
  42. if err = http.ListenAndServe(":"+port, engine); err != nil {
  43. log.Fatal(err)
  44. }
  45. }
  46. func registerRoute(r *gin.Engine, handle *jwt.GinJWTMiddleware) {
  47. r.POST("/login", handle.LoginHandler)
  48. r.NoRoute(handle.MiddlewareFunc(), handleNoRoute())
  49. auth := r.Group("/auth", handle.MiddlewareFunc())
  50. auth.GET("/refresh_token", handle.RefreshHandler)
  51. auth.GET("/hello", helloHandler)
  52. }
  53. func handlerMiddleware(authMiddleware *jwt.GinJWTMiddleware) gin.HandlerFunc {
  54. return func(context *gin.Context) {
  55. errInit := authMiddleware.MiddlewareInit()
  56. if errInit != nil {
  57. log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
  58. }
  59. }
  60. }
  61. func initParams() *jwt.GinJWTMiddleware {
  62. return &jwt.GinJWTMiddleware{
  63. Realm: "test zone",
  64. Key: []byte("secret key"),
  65. Timeout: time.Hour,
  66. MaxRefresh: time.Hour,
  67. IdentityKey: identityKey,
  68. PayloadFunc: payloadFunc(),
  69. IdentityHandler: identityHandler(),
  70. Authenticator: authenticator(),
  71. Authorizator: authorizator(),
  72. Unauthorized: unauthorized(),
  73. TokenLookup: "header: Authorization, query: token, cookie: jwt",
  74. // TokenLookup: "query:token",
  75. // TokenLookup: "cookie:token",
  76. TokenHeadName: "Bearer",
  77. TimeFunc: time.Now,
  78. }
  79. }
  80. func payloadFunc() func(data interface{}) jwt.MapClaims {
  81. return func(data interface{}) jwt.MapClaims {
  82. if v, ok := data.(*User); ok {
  83. return jwt.MapClaims{
  84. identityKey: v.UserName,
  85. }
  86. }
  87. return jwt.MapClaims{}
  88. }
  89. }
  90. func identityHandler() func(c *gin.Context) interface{} {
  91. return func(c *gin.Context) interface{} {
  92. claims := jwt.ExtractClaims(c)
  93. return &User{
  94. UserName: claims[identityKey].(string),
  95. }
  96. }
  97. }
  98. func authenticator() func(c *gin.Context) (interface{}, error) {
  99. return func(c *gin.Context) (interface{}, error) {
  100. var loginVals login
  101. if err := c.ShouldBind(&loginVals); err != nil {
  102. return "", jwt.ErrMissingLoginValues
  103. }
  104. userID := loginVals.Username
  105. password := loginVals.Password
  106. if (userID == "admin" && password == "admin") || (userID == "test" && password == "test") {
  107. return &User{
  108. UserName: userID,
  109. LastName: "Bo-Yi",
  110. FirstName: "Wu",
  111. }, nil
  112. }
  113. return nil, jwt.ErrFailedAuthentication
  114. }
  115. }
  116. func authorizator() func(data interface{}, c *gin.Context) bool {
  117. return func(data interface{}, c *gin.Context) bool {
  118. if v, ok := data.(*User); ok && v.UserName == "admin" {
  119. return true
  120. }
  121. return false
  122. }
  123. }
  124. func unauthorized() func(c *gin.Context, code int, message string) {
  125. return func(c *gin.Context, code int, message string) {
  126. c.JSON(code, gin.H{
  127. "code": code,
  128. "message": message,
  129. })
  130. }
  131. }
  132. func handleNoRoute() func(c *gin.Context) {
  133. return func(c *gin.Context) {
  134. claims := jwt.ExtractClaims(c)
  135. log.Printf("NoRoute claims: %#v\n", claims)
  136. c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
  137. }
  138. }
  139. func helloHandler(c *gin.Context) {
  140. claims := jwt.ExtractClaims(c)
  141. user, _ := c.Get(identityKey)
  142. c.JSON(200, gin.H{
  143. "userID": claims[identityKey],
  144. "userName": user.(*User).UserName,
  145. "text": "Hello World.",
  146. })
  147. }

Demo

Please run _example/basic/server.go file and listen 8000 port.

  1. go run _example/basic/server.go

Download and install httpie CLI HTTP client.

Login API

  1. http -v --json POST localhost:8000/login username=admin password=admin

Output screenshot

api screenshot

Refresh token API

  1. http -v -f GET localhost:8000/auth/refresh_token "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"

Output screenshot

api screenshot

Hello world

Please login as admin and password as admin

  1. http -f GET localhost:8000/auth/hello "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"

Response message 200 OK:

  1. HTTP/1.1 200 OK
  2. Content-Length: 24
  3. Content-Type: application/json; charset=utf-8
  4. Date: Sat, 19 Mar 2016 03:02:57 GMT
  5. {
  6. "text": "Hello World.",
  7. "userID": "admin"
  8. }

Authorization

Please login as test and password as test

  1. http -f GET localhost:8000/auth/hello "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"

Response message 403 Forbidden:

  1. HTTP/1.1 403 Forbidden
  2. Content-Length: 62
  3. Content-Type: application/json; charset=utf-8
  4. Date: Sat, 19 Mar 2016 03:05:40 GMT
  5. Www-Authenticate: JWT realm=test zone
  6. {
  7. "code": 403,
  8. "message": "You don't have permission to access."
  9. }

Use these options for setting the JWT in a cookie. See the Mozilla documentation for more information on these options.

  1. SendCookie: true,
  2. SecureCookie: false, //non HTTPS dev environments
  3. CookieHTTPOnly: true, // JS can't modify
  4. CookieDomain: "localhost:8080",
  5. CookieName: "token", // default jwt
  6. TokenLookup: "cookie:token",
  7. CookieSameSite: http.SameSiteDefaultMode, //SameSiteDefaultMode, SameSiteLaxMode, SameSiteStrictMode, SameSiteNoneMode

Login request flow (using the LoginHandler)

PROVIDED: LoginHandler

This is a provided function to be called on any login endpoint, which will trigger the flow described below.

REQUIRED: Authenticator

This function should verify the user credentials given the gin context (i.e. password matches hashed password for a given user email, and any other authentication logic). Then the authenticator should return a struct or map that contains the user data that will be embedded in the jwt token. This might be something like an account id, role, is_verified, etc. After having successfully authenticated, the data returned from the authenticator is passed in as a parameter into the PayloadFunc, which is used to embed the user identifiers mentioned above into the jwt token. If an error is returned, the Unauthorized function is used (explained below).

OPTIONAL: PayloadFunc

This function is called after having successfully authenticated (logged in). It should take whatever was returned from Authenticator and convert it into MapClaims (i.e. map[string]interface{}). A typical use case of this function is for when Authenticator returns a struct which holds the user identifiers, and that struct needs to be converted into a map. MapClaims should include one element that is [IdentityKey (default is “identity”): some_user_identity]. The elements of MapClaims returned in PayloadFunc will be embedded within the jwt token (as token claims). When users pass in their token on subsequent requests, you can get these claims back by using ExtractClaims.

OPTIONAL: LoginResponse

After having successfully authenticated with Authenticator, created the jwt token using the identifiers from map returned from PayloadFunc, and set it as a cookie if SendCookie is enabled, this function is called. It is used to handle any post-login logic. This might look something like using the gin context to return a JSON of the token back to the user.

Subsequent requests on endpoints requiring jwt token (using MiddlewareFunc)

PROVIDED: MiddlewareFunc

This is gin middleware that should be used within any endpoints that require the jwt token to be present. This middleware will parse the request headers for the token if it exists, and check that the jwt token is valid (not expired, correct signature). Then it will call IdentityHandler followed by Authorizator. If Authorizator passes and all of the previous token validity checks passed, the middleware will continue the request. If any of these checks fail, the Unauthorized function is used (explained below).

OPTIONAL: IdentityHandler

The default of this function is likely sufficient for your needs. The purpose of this function is to fetch the user identity from claims embedded within the jwt token, and pass this identity value to Authorizator. This function assumes [IdentityKey: some_user_identity] is one of the attributes embedded within the claims of the jwt token (determined by PayloadFunc).

OPTIONAL: Authorizator

Given the user identity value (data parameter) and the gin context, this function should check if the user is authorized to be reaching this endpoint (on the endpoints where the MiddlewareFunc applies). This function should likely use ExtractClaims to check if the user has the sufficient permissions to reach this endpoint, as opposed to hitting the database on every request. This function should return true if the user is authorized to continue through with the request, or false if they are not authorized (where Unauthorized will be called).

Logout Request flow (using LogoutHandler)

PROVIDED: LogoutHandler

This is a provided function to be called on any logout endpoint, which will clear any cookies if SendCookie is set, and then call LogoutResponse.

OPTIONAL: LogoutResponse

This should likely just return back to the user the http status code, if logout was successful or not.

Refresh Request flow (using RefreshHandler)

PROVIDED: RefreshHandler:

This is a provided function to be called on any refresh token endpoint. If the token passed in is was issued within the MaxRefreshTime time frame, then this handler will create/set a new token similar to the LoginHandler, and pass this token into RefreshResponse

OPTIONAL: RefreshResponse:

This should likely return a JSON of the token back to the user, similar to LoginResponse

Failures with logging in, bad tokens, or lacking privileges

OPTIONAL Unauthorized:

On any error logging in, authorizing the user, or when there was no token or a invalid token passed in with the request, the following will happen. The gin context will be aborted depending on DisabledAbort, then HTTPStatusMessageFunc is called which by default converts the error into a string. Finally the Unauthorized function will be called. This function should likely return a JSON containing the http error code and error message to the user.