Documentation
¶
Overview ¶
Example ¶
package main
import (
"time"
"github.com/henrylee2cn/faygo"
"github.com/henrylee2cn/faygo/ext/middleware/jwt"
)
func helloHandler(c *faygo.Context) error {
claims := jwt.ExtractClaims(c)
return c.JSON(200, map[string]interface{}{
"userID": claims["id"],
"text": "Hello World.",
})
}
func main() {
r := faygo.New("jwt-test")
// the jwt middleware
authMiddleware := &jwt.FaygoJWTMiddleware{
Realm: "test zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
Authenticator: func(userId string, password string, c *faygo.Context) (string, bool) {
if (userId == "admin" && password == "admin") || (userId == "test" && password == "test") {
return userId, true
}
return userId, false
},
Authorizator: func(userId string, c *faygo.Context) bool {
if userId == "admin" {
return true
}
return false
},
Unauthorized: func(c *faygo.Context, code int, message string) {
c.JSON(code, map[string]interface{}{
"code": code,
"message": message,
})
},
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
TokenLookup: "header:Authorization",
// TokenLookup: "query:token",
// TokenLookup: "cookie:token",
// TokenHeadName is a string in the header. Default value is "Bearer"
TokenHeadName: "Bearer",
// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
TimeFunc: time.Now,
}
r.POST("/login", faygo.HandlerFunc(authMiddleware.LoginHandler))
auth := r.Group("/auth")
auth.Use(authMiddleware.MiddlewareFunc())
{
auth.GET("/hello", faygo.HandlerFunc(helloHandler))
auth.GET("/refresh_token", faygo.HandlerFunc(authMiddleware.RefreshHandler))
}
r.Run()
}
Index ¶
- func ExtractClaims(c *faygo.Context) jwt.MapClaims
- type FaygoJWTMiddleware
- func (mw *FaygoJWTMiddleware) LoginHandler(c *faygo.Context) error
- func (mw *FaygoJWTMiddleware) MiddlewareFunc() faygo.HandlerFunc
- func (mw *FaygoJWTMiddleware) MiddlewareInit() error
- func (mw *FaygoJWTMiddleware) RefreshHandler(c *faygo.Context) error
- func (mw *FaygoJWTMiddleware) TokenGenerator(userID string) string
- type Login
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type FaygoJWTMiddleware ¶
type FaygoJWTMiddleware struct {
// Realm name to display to the user. Required.
Realm string
// signing algorithm - possible values are HS256, HS384, HS512
// Optional, default is HS256.
SigningAlgorithm string
// Secret key used for signing. Required.
Key []byte
// Duration that a jwt token is valid. Optional, defaults to one hour.
Timeout time.Duration
// This field allows clients to refresh their token until MaxRefresh has passed.
// Note that clients can refresh their token in the last moment of MaxRefresh.
// This means that the maximum validity timespan for a token is MaxRefresh + Timeout.
// Optional, defaults to 0 meaning not refreshable.
MaxRefresh time.Duration
// Callback function that should perform the authentication of the user based on userID and
// password. Must return true on success, false on failure. Required.
// Option return user id, if so, user id will be stored in Claim Array.
Authenticator func(userID string, password string, c *faygo.Context) (string, bool)
// Callback function that should perform the authorization of the authenticated user. Called
// only after an authentication success. Must return true on success, false on failure.
// Optional, default to success.
Authorizator func(userID string, c *faygo.Context) bool
// Callback function that will be called during login.
// Using this function it is possible to add additional payload data to the webtoken.
// The data is then made available during requests via c.Get("JWT_PAYLOAD").
// Note that the payload is not encrypted.
// The attributes mentioned on jwt.io can't be used as keys for the map.
// Optional, by default no additional data will be set.
PayloadFunc func(userID string) map[string]interface{}
Unauthorized func(*faygo.Context, int, string)
// Set the identity handler function
IdentityHandler func(jwt.MapClaims) string
// TokenLookup is a string in the form of "<source>:<name>" that is used
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
TokenLookup string
// TokenHeadName is a string in the header. Default value is "Bearer"
TokenHeadName string
// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
TimeFunc func() time.Time
}
FaygoJWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response is returned. On success, the wrapped middleware is called, and the userID is made available as c.Get("userID").(string). Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX
Reference https://github.com/appleboy/gin-jwt
func (*FaygoJWTMiddleware) LoginHandler ¶
func (mw *FaygoJWTMiddleware) LoginHandler(c *faygo.Context) error
LoginHandler can be used by clients to get a jwt token. Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}. Reply will be of the form {"token": "TOKEN"}.
func (*FaygoJWTMiddleware) MiddlewareFunc ¶
func (mw *FaygoJWTMiddleware) MiddlewareFunc() faygo.HandlerFunc
MiddlewareFunc makes FaygoJWTMiddleware implement the Middleware interface.
func (*FaygoJWTMiddleware) MiddlewareInit ¶
func (mw *FaygoJWTMiddleware) MiddlewareInit() error
MiddlewareInit initialize jwt configs.
func (*FaygoJWTMiddleware) RefreshHandler ¶
func (mw *FaygoJWTMiddleware) RefreshHandler(c *faygo.Context) error
RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh. Shall be put under an endpoint that is using the FaygoJWTMiddleware. Reply will be of the form {"token": "TOKEN"}.
func (*FaygoJWTMiddleware) TokenGenerator ¶
func (mw *FaygoJWTMiddleware) TokenGenerator(userID string) string
TokenGenerator handler that clients can use to get a jwt token.