jwt

package module
v0.0.0-...-fd8387d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2019 License: MIT Imports: 7 Imported by: 8

README

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.

Documentation

Index

Constants

View Source
const (
	// ErrKey is used to set error into gin.Context.
	ErrKey = "GIN_JWT_ERROR"
	// PayloadKey is used to set payload of jwt token into gin.Context.
	PayloadKey = "GIN_JWT_PAYLOAD"
	// TokenKey is used to set a jwt token into gin.Context.
	TokenKey = "GIN_JWT_TOKEN"
	// UserKey is used to set a user into gin.Context.
	UserKey = "GIN_JWT_USER"
)

Variables

View Source
var (
	// ErrorAuthorizationHeaderIsEmpty is a error in the case of Authorization header is empty.
	ErrorAuthorizationHeaderIsEmpty = errors.New("Authorization header is empty")

	// ErrorAuthorizationHeaderIsInvalid is a error in the case of Authorization header isn't valid.
	ErrorAuthorizationHeaderIsInvalid = errors.New("Authorization header is invalid")

	// ErrorAuthorizationTokenExpired is an error in the case of Authorization token is expired.
	ErrorAuthorizationTokenExpired = errors.New("Authorization token is expired")

	// ErrorAuthenticationFailed is an error at authentication is failed.
	ErrorAuthenticationFailed = errors.New("Authentication failled")

	// ErrorPermissionDenied is a error at permission is denied.
	ErrorPermissionDenied = errors.New("permission is denied")

	// ErrorUserNotFound is an error in the case of a user not found.
	ErrorUserNotFound = errors.New("user not found")
)

Functions

func Error

func Error(c *gin.Context) interface{}

Error extracts a error from gin.Context.

func ErrorHandler

func ErrorHandler(c *gin.Context)

ErrorHandler handles gin-jwt's errors from gin.Context.

func User

func User(c *gin.Context) interface{}

User extracts the user object from gin.Context that VerifyPerm set.

Types

type Auth

type Auth struct {
	// ExpiryInterval is an interval of expiration that is used to calculate the `exp` claim of JWT.
	ExpiryInterval time.Duration
	// SigningMethod is a method of the signing of JWT token. default is `HS256`.
	SigningMethod string
	// SecretKey is a secret key for signing JWT.
	SecretKey []byte
	// Authenticator authenticates a request and return jwt.MapClaims
	// that contains a user information of the request.
	Authenticator func(*gin.Context) (MapClaims, error)
	// UserFetcher takes a jwt.MapClaims and return a user object.
	UserFetcher func(*gin.Context, MapClaims) (interface{}, error)
	// contains filtered or unexported fields
}

Auth provides useful authorization/authentication functions.

func New

func New(a Auth) (Auth, error)

New returns initialized Auth. If Authenticator or UserFetcher are nil, return the error.

func (Auth) Authenticate

func (a Auth) Authenticate(c *gin.Context)

Authenticate can be used by clients to get a jwt token. Authenticator of Auth is used in this method to authenticate a user request. Authorization token that is a form of `Authorization: Bearer <TOKEN>` is supplied in a response header.

func (Auth) RefreshToken

func (a Auth) RefreshToken(c *gin.Context)

RefreshToken can be used to refresh a token. The token still needs to be valid on refresh. Authorization token that is a form of `Authorization: Bearer <TOKEN>` is supplied in a response header.

func (Auth) VerifyPerm

func (a Auth) VerifyPerm(permitted func(MapClaims) bool) gin.HandlerFunc

VerifyPerm is used to pass a MapClaim to a authorization function. After authorization, use UserFetcher to get a user object by identity, and set it into the gin.Context.

type MapClaims

type MapClaims = jwt.MapClaims

MapClaims is alias of github.com/dgrijalva/jwt-go.MapClaims.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL