jwt

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2021 License: MIT Imports: 13 Imported by: 0

README

gf-jwt

基于GoFrame框架的JWT认证

使用

下载安装

$ go get github.com/kotlin2018/jwt

导入

import "github.com/kotlin2018/jwt"

参数说明

claims["expire"] token的过期时间.

Claims["current_time"] 生成token的当前时间.

r.SetParam("JWT_Payload", claims) 将有效载荷设置到请求中.

r.GetString("Jwt_Token").

请求头中的Authorization字段保存token的值.

例子

查看示例 example/auth/auth.go , 使用 ExtractClaims 可以自定义用户数据.

Demo

运行 example/server/server.go8000端口.

$ go run example/server/server.go

api screenshot

通过 httpie ,在命令行来测试下效果.

登录接口:
$ http -v --form  POST localhost:8000/login username=admin password=admin

命令行输出

api screenshot

刷新 token 接口:
$ http -v -f GET localhost:8000/user/refresh_token "Authorization:Bearer xxxxxxxxx"  "Content-Type: application/json"

命令行输出

api screenshot

info 接口

我们使用用户名 admin 和密码 admin 测试一下 info 接口的返回

$ http -f GET localhost:8000/user/info "Authorization:Bearer xxxxxxxxx"  "Content-Type: application/json"

命令行输出

api screenshot

用户验证接口

我们用未授权的 token 来测试 info 接口的返回

$ http -f GET localhost:8000/user/info "Authorization:Bearer xxxxxxxxx"  "Content-Type: application/json"

命令行输出

api screenshot

再次感谢https://github.com/appleboy/gin-jwt

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingSecretKey 表示需要密钥
	ErrMissingSecretKey = errors.New("secret key is required")

	// ErrForbidden when HTTP status 403 is given
	ErrForbidden = errors.New("you don't have permission to access this resource")

	// ErrMissingAuthenticatorFunc indicates Authenticator is required
	ErrMissingAuthenticatorFunc = errors.New("GfJWTMiddleware.Authenticator func is undefined")

	// ErrMissingLoginValues indicates a user tried to authenticate without username or password
	ErrMissingLoginValues = errors.New("missing Username or Password")

	// ErrFailedAuthentication indicates authentication failed, could be faulty username or password
	ErrFailedAuthentication = errors.New("incorrect Username or Password")

	// ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
	ErrFailedTokenCreation = errors.New("failed to create JWT Token")

	// ErrExpiredToken indicates JWT token has expired. Can't refresh.
	ErrExpiredToken = errors.New("token is expired")

	// ErrInvalidToken indicates JWT token has invalid. Can't refresh.
	ErrInvalidToken = errors.New("token is invalid")

	// ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
	ErrEmptyAuthHeader = errors.New("auth header is empty")

	// ErrMissingExpField missing exp field in token
	ErrMissingExpField = errors.New("missing exp field")

	// ErrWrongFormatOfExp field must be float64 format
	ErrWrongFormatOfExp = errors.New("exp must be float64 format")

	// ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name
	ErrInvalidAuthHeader = errors.New("auth header is invalid")

	// ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
	ErrEmptyQueryToken = errors.New("query token is empty")

	// ErrEmptyCookieToken can be thrown if authing with a cookie, the token cokie is empty
	ErrEmptyCookieToken = errors.New("cookie token is empty")

	// ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
	ErrEmptyParamToken = errors.New("parameter token is empty")

	// ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512
	ErrInvalidSigningAlgorithm = errors.New("invalid signing algorithm")

	// ErrNoPrivKeyFile indicates that the given private key is unreadable
	ErrNoPrivKeyFile = errors.New("private key file unreadable")

	// ErrNoPubKeyFile indicates that the given public key is unreadable
	ErrNoPubKeyFile = errors.New("public key file unreadable")

	// ErrInvalidPrivKey indicates that the given private key is invalid
	ErrInvalidPrivKey = errors.New("private key invalid")

	// ErrInvalidPubKey indicates the the given public key is invalid
	ErrInvalidPubKey = errors.New("public key invalid")

	// ErrMissingIdentity identity key and identity value is null
	ErrMissingIdentity = errors.New("payload don't have identity key and identity value")
)
View Source
var (
	Auth    *GfJWTMiddleware
	Name    string // 显示给用户的名称,这个参数必须要有。
	Key     string // 用于签名的密钥。 这个参数必须要有。
	Timeout string // jwt令牌有效的持续时间。 可选,默认为一小时,时间单位为:小时。
	// 此字段允许客户端刷新令牌,直到MaxRefresh通过。可选,默认为0,表示不可刷新。
	//
	// 请注意: 客户端可以在MaxRefresh的最后时刻刷新其令牌,这意味着令牌的最大有效时间跨度为TokenTime + MaxRefresh。
	MaxRefresh string // 此字段允许客户端刷新令牌,直到MaxRefresh通过。
)
View Source
var (
	// 默认身份密钥
	IdentityKey = "identity"
)

Functions

func Authenticator

func Authenticator(r *ghttp.Request) (interface{}, error)

返回值interface{} 就是 JWT_Payload对应的值,即: interface{} = r.Get("JWT_Payload")

func CORS

func CORS(r *ghttp.Request)

func IdentityHandler

func IdentityHandler(r *ghttp.Request) interface{}

IdentityHandler从JWT获取身份并为每个请求设置身份使用此函数,通过r.GetParam(“ id”)获取身份。

func JWTAuth

func JWTAuth(pattern ...string)

JWTAuth JwtToken中间件。

可选参数<pattern> 不能为空,<pattern>用法如下:

pattern[0] = "POST:/login"

pattern[1] = "ALL:/refresh_token"

pattern[2] = "ALL:/logout"

func LoginResponse

func LoginResponse(r *ghttp.Request, code int, token string, expire time.Time)

============ ============ ============ ============ LoginResponse 用于定义自定义的登录成功回调函数。

func LogoutResponse

func LogoutResponse(r *ghttp.Request, code int)

LogoutResponse is used to set token blacklist.

func MiddlewareAuth

func MiddlewareAuth(r *ghttp.Request)

func RefreshResponse

func RefreshResponse(r *ghttp.Request, code int, token string, expire time.Time)

func Unauthorized

func Unauthorized(r *ghttp.Request, code int, message string)

Unauthorized 用于定义自定义的未经授权的回调函数。

Types

type GfJWTMiddleware

type GfJWTMiddleware struct {
	// 显示给用户的名称,这个参数必须要有。默认值: "gf jwt"
	Name string

	// 签名算法-可能的值是HS256,HS384,HS512可选,默认值为: HS256。
	SigningAlgorithm string

	// 用于签名的密钥。 这个参数必须要有。
	Key []byte

	// jwt令牌有效的持续时间。 可选,默认为一小时。
	Timeout time.Duration

	// 此字段允许客户端刷新令牌,直到MaxRefresh通过。
	// 请注意,客户端可以在MaxRefresh的最后时刻刷新其令牌。
	// 这意味着令牌的最大有效时间跨度为TokenTime + MaxRefresh。 可选,默认为0,表示不可刷新。
	MaxRefresh time.Duration

	// 应基于登录信息执行用户身份验证的回调函数。
	// 必须返回用户数据作为用户标识符,它将存储在Claim Array中。
	// 必需的。 检查错误(e),以确定适当的错误消息。
	Authenticator func(r *ghttp.Request) (interface{}, error)

	// 仅在身份验证成功后调用。 成功必须返回true,失败必须返回false。 可选,默认为成功。
	Authorizer func(data interface{}, r *ghttp.Request) bool

	// 登录期间将调用的回调函数。
	// 使用此功能可以向网络令牌添加其他有效载荷数据。
	// 然后在请求期间通过c.Get(“ JWT_PAYLOAD”)使数据可用。
	// 请注意,有效负载未加密。 jwt.io上提到的属性不能用作地图的键。
	// 可选,默认情况下不会设置其他数据。
	PayloadFunc func(data interface{}) MapClaims

	// 用户可以定义自己的未经授权的功能。
	Unauthorized func(*ghttp.Request, int, string)

	// 登陆成功之后的回调函数
	LoginResponse func(*ghttp.Request, int, string, time.Time)

	// 刷新Token令牌
	RefreshResponse func(*ghttp.Request, int, string, time.Time)

	// 注销token后的回调函数
	LogoutResponse func(*ghttp.Request, int)

	// 设置身份处理程序功能
	IdentityHandler func(*ghttp.Request) interface{}

	// 将 GfJWTMiddleware实例注册成中间件
	Use func(*ghttp.Request)

	// 设置身份密钥
	IdentityKey string

	// TokenLookup 是“ <source>:<name>”形式的字符串,用于从请求中提取令牌。
	//
	// 默认值: "header:Authorization"。
	//
	// 可选值:
	//
	// - "header:<name>"
	//
	// - "query:<name>"
	//
	// - "cookie:<name>"
	TokenLookup string

	// TokenHeadName 是标题中的字符串,默认值为: "Bearer"
	TokenHeadName string

	// TimeFunc 提供当前时间。 您可以覆盖它以使用其他时间值。 这对于测试或服务器使用不同于令牌的时区很有用。
	TimeFunc func() time.Time

	// 当JWT中间件发生故障时的HTTP状态消息。 检查错误(e),以确定适当的错误消息。
	HTTPStatusMsgFunc func(e error, r *ghttp.Request) string

	// 非对称算法的私钥文件
	PrivateKeyFile string

	// 非对称算法的公钥文件
	PublicKeyFile string

	// (可选) 将令牌作为Cookie返回
	SendCookie bool

	// 允许不安全的Cookie通过HTTP进行开发
	SecureCookie bool

	// 允许访问客户端的Cookie以进行开发
	CookieHTTPOnly bool

	// 允许更改Cookie域以进行开发
	CookieDomain string

	// SendAuthorization 允许每个请求的返回授权标头
	SendAuthorization bool

	// 禁用上下文的abort()。
	DisabledAbort bool

	// CookieName允许更改Cookie名称以进行开发,默认值: "jwt"
	CookieName string

	// 缓存适配器
	CacheAdapter gcache.Adapter
	// contains filtered or unexported fields
}

GfJWTMiddleware 提供了Json-Web-Token身份验证实现。

失败时,将返回401 HTTP响应;成功后,将调用包装的中间件,并以c.Get(“ userID”)。(string)的形式提供userID。

用户可以通过将json请求发布到LoginHandler来获得令牌,然后需要在Authentication标头中传递令牌。

示例:授权:承载者XXX_TOKEN_XXX

func New

func (*GfJWTMiddleware) CheckTokenExpire

func (m *GfJWTMiddleware) CheckTokenExpire(r *ghttp.Request) (jwt.MapClaims, string, error)

CheckTokenExpire 检查令牌是否过期

func (*GfJWTMiddleware) GenerateToken

func (m *GfJWTMiddleware) GenerateToken(data interface{}) (string, time.Time, error)

客户端可以用来获取jwt令牌的TokenGenerator方法。

func (*GfJWTMiddleware) GetClaimsFromJWT

func (m *GfJWTMiddleware) GetClaimsFromJWT(r *ghttp.Request) (MapClaims, string, error)

GetClaimsFromJWT 从JWT令牌获取claims

func (*GfJWTMiddleware) LoginHandler

func (m *GfJWTMiddleware) LoginHandler(r *ghttp.Request)

LoginHandler 客户端可以使用LoginHandler获得jwt令牌。

该函数内部逻辑依赖于 Authenticator(),LoginResponse() 这两个函数的具体实现。

有效负载必须为{“ username”:“ USERNAME”,“ password”:“ PASSWORD”}形式的json。

回复的格式为{“ token”:“ TOKEN”}。: Authenticator(),LoginResponse()

func (*GfJWTMiddleware) LogoutHandler

func (m *GfJWTMiddleware) LogoutHandler(r *ghttp.Request)

LogoutHandler 可用于注销令牌。 令牌仍然需要在注销时有效。 注销令牌会将未过期的令牌列入黑名单

func (*GfJWTMiddleware) MiddlewareFunc

func (m *GfJWTMiddleware) MiddlewareFunc() ghttp.HandlerFunc

MiddlewareFunc 使GfJWTMiddleware实现Middleware接口。内部只调用了middlewareImpl()

func (*GfJWTMiddleware) MiddlewareInit

func (m *GfJWTMiddleware) MiddlewareInit() error

func (*GfJWTMiddleware) ParseToken

func (m *GfJWTMiddleware) ParseToken(r *ghttp.Request) (*jwt.Token, error)

ParseToken parse jwt token 该函数内部有 r.SetParam("Jwt_Token", token)

func (*GfJWTMiddleware) RefreshHandler

func (m *GfJWTMiddleware) RefreshHandler(r *ghttp.Request)

RefreshHandler 可用于刷新令牌。令牌在刷新时仍然需要有效。应放置在使用GfJWTMiddleware的端点下。回复的格式为{“ token”:“ TOKEN”}

func (*GfJWTMiddleware) RefreshToken

func (m *GfJWTMiddleware) RefreshToken(r *ghttp.Request) (string, time.Time, error)

RefreshToken 刷新令牌并检查令牌是否已过期

type MapClaims

type MapClaims map[string]interface{}

MapClaims 如果您不提供,这是默认的声明类型。使用map [string] interface {}进行JSON解码

func ExtractClaims

func ExtractClaims(r *ghttp.Request) MapClaims

ExtractClaims 帮助提取JWT claims

func PayloadFunc

func PayloadFunc(data interface{}) MapClaims

PayloadFunc是一个回调函数,将在登录期间被调用。

使用此功能可以向网络令牌添加其他有效载荷数据。 然后在请求期间通过c.Get(“ JWT_PAYLOAD”)使数据可用。 请注意,有效负载未加密。 jwt.io上提到的属性不能用作map的键。 可选,默认情况下不会设置其他数据。

Directories

Path Synopsis
api

Jump to

Keyboard shortcuts

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