README
¶
jwt
Generate and parse token based on jwt library.
Example of use
Example 1: common fields jwt
import "github.com/18721889353/sunshine/pkg/jwt"
jwt.Init(
// jwt.WithSigningKey("123456"), // key
// jwt.WithExpire(time.Hour), // expiry time
// jwt.WithSigningMethod(jwt.HS512), // encryption method, default is HS256, can be set to HS384, HS512
)
uid := "123"
name := "admin"
// generate token
token, err := jwt.GenerateToken(uid, name)
// handle err
// parse token
claims, err := jwt.ParseToken(token)
// handle err
// verify
if claims.Uid != uid || claims.Name != name {
print("verify failed")
return
}
Example 2: custom fields jwt
import "github.com/18721889353/sunshine/pkg/jwt"
jwt.Init(
// jwt.WithSigningKey("123456"), // key
// jwt.WithExpire(time.Hour), // expiry time
// jwt.WithSigningMethod(jwt.HS512), // encryption method, default is HS256, can be set to HS384, HS512
)
fields := jwt.KV{"id": 123, "foo": "bar"}
// generate token
token, err := jwt.GenerateCustomToken(fields)
// handle err
// parse token
claims, err := jwt.ParseCustomToken(token)
// handle err
// verify
id, isExist1 := claims.Get("id")
foo, isExist2 := claims.Get("foo")
if !isExist1 || !isExist2 || int(id.(float64)) != fields["id"].(int) || foo.(string) != fields["foo"].(string) {
print("verify failed")
return
}
Documentation
¶
Overview ¶
Package jwt is token generation and validation.
Index ¶
- Variables
- func GenerateCustomToken(kv map[string]interface{}) (string, error)
- func GenerateToken(uid string, name ...string) (string, error)
- func Init(opts ...Option)
- func RefreshCustomToken(tokenString string) (string, error)
- func RefreshToken(tokenString string) (string, error)
- type Claims
- type CustomClaims
- type KV
- type Option
Constants ¶
This section is empty.
Variables ¶
View Source
var ( // HS256 Method HS256 = jwt.SigningMethodHS256 // HS384 Method HS384 = jwt.SigningMethodHS384 // HS512 Method HS512 = jwt.SigningMethodHS512 )
View Source
var ErrTokenExpired = jwt.ErrTokenExpired
ErrTokenExpired expired
Functions ¶
func GenerateCustomToken ¶
GenerateCustomToken generate token by custom fields
func GenerateToken ¶
GenerateToken generate token by uid and name
func RefreshCustomToken ¶
RefreshCustomToken refresh custom token
func RefreshToken ¶
RefreshToken refresh token
Types ¶
type CustomClaims ¶
type CustomClaims struct { Fields KV `json:"fields"` jwt.RegisteredClaims }
CustomClaims custom fields claims
func ParseCustomToken ¶
func ParseCustomToken(tokenString string) (*CustomClaims, error)
ParseCustomToken parse token
func (*CustomClaims) Get ¶
func (c *CustomClaims) Get(key string) (val interface{}, isExist bool)
Get custom field value by key, if not found, return false
type Option ¶
type Option func(*options)
Option set the jwt options.
func WithSigningMethod ¶
func WithSigningMethod(sm *jwt.SigningMethodHMAC) Option
WithSigningMethod set signing method value
Click to show internal directories.
Click to hide internal directories.