最新:https://github.com/golang-jwt/jwt
type SigningMethod
定义了验证的方法接口
type SigningMethod interface {
// Returns nil if signature is valid
Verify(signingString, signature string, key interface{}) error
// Returns encoded signature or error
Sign(signingString string, key interface{}) (string, error)
// returns the alg identifier for this method (example: 'HS256')
Alg() string
}
type SigningMethodECDSA
实现了SigningMethod接口
type SigningMethodECDSA struct {
Name string
Hash crypto.Hash
KeySize int
CurveBits int
}
var (
SigningMethodES256 *SigningMethodECDSA
SigningMethodES384 *SigningMethodECDSA
SigningMethodES512 *SigningMethodECDSA
)
func (m SigningMethodECDSA) Alg() string
func (m SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error)
func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error
type Keyfunc
type Keyfunc func(*Token) (interface{}, error)
type MapClaims
type MapClaims map[string]interface{}
type StandardClaims
type StandardClaims struct {
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
Id string `json:"jti,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Issuer string `json:"iss,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Subject string `json:"sub,omitempty"`
}
func (c StandardClaims) Valid() error:验证standardclaims的合法性
func (c StandardClaims) VerifyAudience(cmp string, req bool) bool:验证standardclaims的合法性
func (c StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool
func (c StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool
func (c StandardClaims) VerifyIssuer(cmp string, req bool) bool
func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool
type Token
type Token struct {
Raw string // The raw token. Populated when you Parse a token
Method SigningMethod // The signing method used or to be used
Header map[string]interface{} // The first segment of the token
Claims Claims // The second segment of the token
Signature string // The third segment of the token. Populated when you Parse a token
Valid bool // Is the token valid? Populated when you Parse/Verify a token
}
func (t *Token) SignedString(key interface{}) (string, error):生成已签名的令牌
无claims
func New(method SigningMethod) *Token:创建一个新的令牌
func main() {
calims :=make(jwt.MapClaims)
calims["name"] = "zhangsan"
calims["age"] = 20
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = calims
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte("mysalt"))
fmt.Println(tokenString, err)
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHBpcmVkIjoxNTY2NTU5MjE1LCJ0aW1lc3RyYXAiOjE1NjY1NTU2MTV9.7m83aVguSGcVJHnZ51_nm268HnRYWj-xaIzOXUp-ayU <nil>
func CreateJWT() string{
claims := jwt.StandardClaims{}
claims.ExpiresAt = time.Now().Add(time.Second * 1).Unix()
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
tokenString, err := token.SignedString(MySigningKey)
fmt.Println(tokenString, err)
}
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error)
func main() {
tokenString :="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHBpcmVkIjoxNTY2NTU5MjE1LCJ0aW1lc3RyYXAiOjE1NjY1NTU2MTV9.7m83aVguSGcVJHnZ51_nm268HnRYWj-xaIzOXUp-ayU"
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("mysalt"), nil
})
if token.Valid { //有效
fmt.Println("good work")
} else if ve, ok := err.(*jwt.ValidationError); ok { //错误被捕捉
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
//格式错误
fmt.Println("That's not even a token")
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
//过期或还没激活
fmt.Println("Token is either expired or not active yet")
} else {
//signature is invalid
fmt.Println("Couldn't handle this token:", err)
}
} else { //错误无法捕捉
fmt.Println("Couldn't handle this token:", err)
}
}
good work
有claims
func NewWithClaims(method SigningMethod, claims Claims) *Token
mySigningKey := []byte("AllYourBase")
type MyCustomClaims struct {
Foo string `json:"foo"`
jwt.StandardClaims
}
// Create the Claims
claims := MyCustomClaims{
"bar",
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
Issuer: "test",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)
--------------------------------------------------------------------------------
mySigningKey := []byte("AllYourBase")
// Create the Claims
claims := &jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
Issuer: "test",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)
fmt.Printf("%v %v", ss, err)
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
type MyCustomClaims struct {
Foo string `json:"foo"`
jwt.StandardClaims
}
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("AllYourBase"), nil
})
if err !=nil {
if ve, ok := err.(*jwt.ValidationError); ok { //错误被捕捉
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
//格式错误
fmt.Println("That's not even a token")
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
//过期或还没激活
fmt.Println("Token is either expired or not active yet")
} else {
//signature is invalid
fmt.Println("Couldn't handle this token:", err)
}
}
//错误无法捕捉
fmt.Println("Couldn't handle this token:", err)
}
if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
}else { // 上面的错误可以不捕捉
fmt.Println("Couldn't handle this token:", err)
}
无claims创建,有claims解析
func CreateJWT() string{
claims := jwt.StandardClaims{}
claims.ExpiresAt = time.Now().Add(time.Second * 1).Unix()
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
tokenString, err := token.SignedString(MySigningKey)
fmt.Println(tokenString, err)
return tokenString
}
func main() {
tokenString := CreateJWT()
token,err := jwt.ParseWithClaims(tokenString,&jwt.StandardClaims{},func(token *jwt.Token) (interface{}, error) {
return MySigningKey, nil
})
if claims, ok := token.Claims.(*jwt.StandardClaims); ok && token.Valid {
fmt.Println(claims)
}else { // 上面的错误可以不捕捉
fmt.Println("Couldn't handle this token:", err)
}
}
func CreateJWT() string {
calims := make(jwt.MapClaims)
calims["name"] = "zhangsan"
calims["age"] = 20
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = calims
tokenString, err := token.SignedString([]byte("mysalt"))
fmt.Println(tokenString, err)
return tokenString
}
func main() {
tokenString := CreateJWT()
token, err := jwt.ParseWithClaims(tokenString, &jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("mysalt"), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println(claims)
} else { // 上面的错误可以不捕捉
fmt.Println("Couldn't handle this token:", err)
}
}
常见的token报存用户信息
package main
import (
"fmt"
"github.com/golang-jwt/jwt"
"time"
)
var (
MySigningKey = []byte("mysalt")
)
type MyCustomClaims struct {
jwt.StandardClaims
UserId string `json:"UserId"`
}
func CreatJWT() string{
userId := "xaspln001"
claims := MyCustomClaims{
jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
Issuer: "jw",
},
userId,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(MySigningKey)
fmt.Println(tokenString, err)
return tokenString
}
func main() {
tokenString := CreatJWT()
token,err := jwt.ParseWithClaims(tokenString,&MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return MySigningKey, nil
})
if err != nil {
fmt.Println("请登入!")
}
if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
fmt.Printf("%v %v", claims.UserId,claims.ExpiresAt)
} else {
fmt.Println("请登入!")
}
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzExOTQxOTUsImlzcyI6Imp3IiwiVXNlcklkIjoieGFzcGxuMDAxIn0.58KuTNAMPUebivq3mJLrZzjZ140sn9g-0YHCvJxzTlg <nil>
xaspln001 1571194195