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:
- Authenticate (for issuing a token)
- RefreshToken (for refreshing a expiration of token)
- VerifyPerm (the helper for verify permission)
It uses only Authorization
HTTP header to exchange a token.
$ go get github.com/kyfk/gin-jwt
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
}
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.
Appleboy's repository provides authorization features. Although I wanted a more flexible feature to manage several roles. Finally, I decided to create this repository.