kyfk / gin-jwt

The simplest way of auth[orize/enticate] for Gin framework.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

gin-jwt

GoDoc Build Status Go Report Card codecov codebeat badge

This is the simplest authorization/authentication middleware for Gin Web Framework.

It uses jwt-go to provide a jwt authentication middleware.

It provides additional bellow 3 handlers:

It uses only Authorization HTTP header to exchange a token.

Installation

$ go get github.com/kyfk/gin-jwt

Example

See the Complete Example for more details.

func main() {
    auth, err := jwt.New(jwt.Auth{
        SecretKey: []byte("must change here"),

        // Authenticator authenticates a request and return jwt.MapClaims
        // that contains a user information of the request.
        Authenticator: func(c *gin.Context) (jwt.MapClaims, error) {
            var loginForm LoginForm
            if err := c.ShouldBind(&loginForm); err != nil {
                return nil, jwt.ErrorAuthenticationFailed
            }

            u, ok := authenticate(req.Username, req.Password)
            if ok {
                return nil, jwt.ErrorAuthenticationFailed
            }

            return jwt.MapClaims{
                "username": u.Username,
                "role":     u.Role,
            }, nil
        },

        // UserFetcher takes a jwt.MapClaims and return a user object.
        UserFetcher: func(c *gin.Context, claims jwt.MapClaims) (interface{}, error) {
            username, ok := claims["username"].(string)
            if !ok {
                return nil, nil
            }
            return findByUsername(username)
        },
    })

    // some lines

    e.Use(jwt.ErrorHandler)

    // issue authorization token
    e.POST("/login", auth.AuthenticateHandler)

    // refresh token expiration
    e.POST("/auth/refresh_token", auth.RefreshHandler)

    // role management
    e.GET("/operator/hello", Operator(auth), SayHello) // this is only for Operator
    e.GET("/admin/hello", Admin(auth), SayHello) // this is only for Admin
}

Error Handling

The handlers set an error into the gin.Context if it occurred.

Let's see the ErrorHandler. That's middleware for error handling.

If you want to handle errors yourself, copy above middleware and fix it.

Inspired By

Appleboy's repository provides authorization features. Although I wanted a more flexible feature to manage several roles. Finally, I decided to create this repository.

About

The simplest way of auth[orize/enticate] for Gin framework.

License:MIT License


Languages

Language:Go 97.0%Language:Makefile 3.0%