auth.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package middleware
  2. import (
  3. "github.com/kataras/iris/v12"
  4. "github.com/kataras/iris/v12/middleware/jwt"
  5. "time"
  6. "xps/utils"
  7. )
  8. var (
  9. sigKey = []byte("signature_hmac_secret_shared_key")
  10. encKey = []byte("GCM_AES_256_secret_shared_key_32")
  11. )
  12. type XClaims struct {
  13. OcId int64 `json:"ocId"`
  14. OcTypeId int64 `json:"ocTypeId"`
  15. UserId int64 `json:"userId"`
  16. }
  17. type xHeaders struct {
  18. AppKey string `header:"Appkey,required"`
  19. AppSecret string `header:"Appsecret,required"`
  20. Authorization string `header:"Authorization,required"`
  21. }
  22. func GenerateToken(ocId, ocTypeId, userId int64) (string, error) {
  23. signer := jwt.NewSigner(jwt.HS256, sigKey, 10*time.Minute)
  24. claims := XClaims{OcId: ocId, OcTypeId: ocTypeId, UserId: userId}
  25. token, err := signer.Sign(claims)
  26. if err != nil {
  27. return "", err
  28. }
  29. return string(token), nil
  30. }
  31. func AuthToken(ctx iris.Context) {
  32. var hs xHeaders
  33. if err := ctx.ReadHeaders(&hs); err != nil {
  34. _ = ctx.JSON(utils.HttpStatusErr(utils.HTTP_STATUS_ERR, err.Error(), nil))
  35. return
  36. }
  37. token := hs.Authorization[7:]
  38. verifiedToken, err := jwt.Verify(jwt.HS256, sigKey, []byte(token))
  39. if err != nil {
  40. _ = ctx.JSON(utils.HttpStatusErr(utils.HTTP_STATUS_UNAUTHORIZED, "请重新登录", nil))
  41. return
  42. }
  43. var claims XClaims
  44. err = verifiedToken.Claims(&claims)
  45. if err != nil {
  46. _ = ctx.JSON(utils.HttpStatusErr(utils.HTTP_STATUS_UNAUTHORIZED, "请重新登录", nil))
  47. return
  48. }
  49. ctx.Values().Set("appKey", hs.AppKey)
  50. ctx.Values().Set("appSecret", hs.AppSecret)
  51. // Get the verified and decoded claims.
  52. //xClaims := jwt.Get(ctx).(*XClaims)
  53. // Optionally, get token information if you want to work with them.
  54. // Just an example on how you can retrieve all the standard claims (set by signer's max age, "exp").
  55. //standardClaims := jwt.GetVerifiedToken(ctx).StandardClaims
  56. //timeLeft := standardClaims.Timeleft()
  57. ocId := claims.OcId
  58. ocTypeId := claims.OcTypeId
  59. userId := claims.UserId
  60. ctx.Values().Set("ocId", ocId)
  61. ctx.Values().Set("ocTypeId", ocTypeId)
  62. ctx.Values().Set("userId", userId)
  63. ctx.Next()
  64. }