| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package middleware
- import (
- "github.com/kataras/iris/v12"
- "github.com/kataras/iris/v12/middleware/jwt"
- "time"
- "xps/utils"
- )
- var (
- sigKey = []byte("signature_hmac_secret_shared_key")
- encKey = []byte("GCM_AES_256_secret_shared_key_32")
- )
- type XClaims struct {
- OcId int64 `json:"ocId"`
- OcTypeId int64 `json:"ocTypeId"`
- UserId int64 `json:"userId"`
- }
- type xHeaders struct {
- AppKey string `header:"Appkey,required"`
- AppSecret string `header:"Appsecret,required"`
- Authorization string `header:"Authorization,required"`
- }
- func GenerateToken(ocId, ocTypeId, userId int64) (string, error) {
- signer := jwt.NewSigner(jwt.HS256, sigKey, 10*time.Minute)
- claims := XClaims{OcId: ocId, OcTypeId: ocTypeId, UserId: userId}
- token, err := signer.Sign(claims)
- if err != nil {
- return "", err
- }
- return string(token), nil
- }
- func AuthToken(ctx iris.Context) {
- var hs xHeaders
- if err := ctx.ReadHeaders(&hs); err != nil {
- _ = ctx.JSON(utils.HttpStatusErr(utils.HTTP_STATUS_ERR, err.Error(), nil))
- return
- }
- token := hs.Authorization[7:]
- verifiedToken, err := jwt.Verify(jwt.HS256, sigKey, []byte(token))
- if err != nil {
- _ = ctx.JSON(utils.HttpStatusErr(utils.HTTP_STATUS_UNAUTHORIZED, "请重新登录", nil))
- return
- }
- var claims XClaims
- err = verifiedToken.Claims(&claims)
- if err != nil {
- _ = ctx.JSON(utils.HttpStatusErr(utils.HTTP_STATUS_UNAUTHORIZED, "请重新登录", nil))
- return
- }
- ctx.Values().Set("appKey", hs.AppKey)
- ctx.Values().Set("appSecret", hs.AppSecret)
- // Get the verified and decoded claims.
- //xClaims := jwt.Get(ctx).(*XClaims)
- // Optionally, get token information if you want to work with them.
- // Just an example on how you can retrieve all the standard claims (set by signer's max age, "exp").
- //standardClaims := jwt.GetVerifiedToken(ctx).StandardClaims
- //timeLeft := standardClaims.Timeleft()
- ocId := claims.OcId
- ocTypeId := claims.OcTypeId
- userId := claims.UserId
- ctx.Values().Set("ocId", ocId)
- ctx.Values().Set("ocTypeId", ocTypeId)
- ctx.Values().Set("userId", userId)
- ctx.Next()
- }
|