jwt.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package jwtwrapper
  4. import (
  5. "fmt"
  6. "time"
  7. "github.com/dgrijalva/jwt-go"
  8. )
  9. var jwtSecret []byte
  10. // SetSecret 传入jwt密钥
  11. // 输入:secret 密钥
  12. func SetSecret(secret string) {
  13. jwtSecret = []byte(secret)
  14. return
  15. }
  16. // GenToken 生成token
  17. // 输入:
  18. // id 有可能是用户id
  19. // issuer 发行人名称
  20. // subject 自定义信息,如json数据:{"username": "1@email.com", "password":"123456"}
  21. // seconds 过期秒数
  22. // 输出:token或错误
  23. func GenToken(id, issuer, subject string, seconds time.Duration) (string, error) {
  24. if len(jwtSecret) == 0 {
  25. return "", fmt.Errorf("jwtSecret is empty.")
  26. }
  27. nowTime := time.Now()
  28. expireTime := nowTime.Add(seconds)
  29. claims := jwt.StandardClaims{
  30. ExpiresAt: expireTime.Unix(),
  31. Id: id,
  32. Issuer: issuer,
  33. Subject: subject,
  34. }
  35. tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  36. token, err := tokenClaims.SignedString(jwtSecret)
  37. return token, err
  38. }
  39. // ParseToken 解析token成明文信息
  40. // 输入:token 用户登录后的请求
  41. // 输出:明文结构或错误
  42. func ParseToken(token string) (*jwt.StandardClaims, error) {
  43. tokenClaims, err := jwt.ParseWithClaims(
  44. token,
  45. &jwt.StandardClaims{},
  46. func(token *jwt.Token) (interface{}, error) {
  47. return jwtSecret, nil
  48. },
  49. )
  50. if tokenClaims != nil {
  51. claims, ok := tokenClaims.Claims.(*jwt.StandardClaims)
  52. if !ok {
  53. return nil, err
  54. }
  55. if tokenClaims.Valid {
  56. return claims, nil
  57. }
  58. return claims, err
  59. }
  60. return nil, err
  61. }