jwt.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package util
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. "github.com/dgrijalva/jwt-go"
  7. "kpt.xdmy/pkg/setting"
  8. )
  9. var JwtSecret = []byte(setting.AppSetting.JwtSecret)
  10. type Claims struct {
  11. Username string `json:"username"`
  12. Password string `json:"password"`
  13. jwt.StandardClaims
  14. }
  15. func GenerateToken(username, password string) (string, error) {
  16. nowTime := time.Now()
  17. expireTime := nowTime.Add(12 * time.Hour)
  18. claims := Claims{
  19. username,
  20. EncodeMD5(password),
  21. jwt.StandardClaims{
  22. ExpiresAt: expireTime.Unix(),
  23. Issuer: "https://github.com/kptyun/go-admin/",
  24. },
  25. }
  26. tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  27. token, err := tokenClaims.SignedString(JwtSecret)
  28. return token, err
  29. }
  30. func ParseToken(token string) (*Claims, error) {
  31. tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
  32. return JwtSecret, nil
  33. })
  34. if tokenClaims != nil {
  35. if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
  36. return claims, nil
  37. }
  38. }
  39. return nil, err
  40. }
  41. func GetIdFromClaims(key string, claims jwt.Claims) string {
  42. v := reflect.ValueOf(claims)
  43. if v.Kind() == reflect.Map {
  44. for _, k := range v.MapKeys() {
  45. value := v.MapIndex(k)
  46. if fmt.Sprintf("%s", k.Interface()) == key {
  47. return fmt.Sprintf("%v", value.Interface())
  48. }
  49. }
  50. }
  51. return ""
  52. }