jwt.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package jwt
  2. import (
  3. "fmt"
  4. "kpt-tmr-group/config"
  5. "reflect"
  6. "time"
  7. "github.com/dgrijalva/jwt-go"
  8. )
  9. var jwtSecret = []byte(config.Options().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(4 * time.Hour)
  18. claims := Claims{
  19. username,
  20. 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. return tokenClaims.SignedString(jwtSecret)
  28. }
  29. func ParseToken(token string) (*Claims, error) {
  30. tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
  31. return jwtSecret, nil
  32. })
  33. if tokenClaims != nil {
  34. if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
  35. return claims, nil
  36. }
  37. }
  38. return nil, err
  39. }
  40. func GetIdFromClaims(key string, claims jwt.Claims) string {
  41. v := reflect.ValueOf(claims)
  42. if v.Kind() == reflect.Map {
  43. for _, k := range v.MapKeys() {
  44. value := v.MapIndex(k)
  45. if fmt.Sprintf("%s", k.Interface()) == key {
  46. return fmt.Sprintf("%v", value.Interface())
  47. }
  48. }
  49. }
  50. return ""
  51. }