You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.0 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. jwt "github.com/dgrijalva/jwt-go"
  6. )
  7. const (
  8. signingKey = "this is the secret signing key"
  9. )
  10. var createdToken string
  11. func initializeToken() {
  12. var err error
  13. createdToken, err = newToken()
  14. if err != nil {
  15. fmt.Println("Creating token failed")
  16. }
  17. }
  18. func newToken() (string, error) {
  19. signingKeyB := []byte(signingKey)
  20. // Create the token
  21. token := jwt.New(jwt.SigningMethodHS256)
  22. // Set some claims
  23. claims := make(jwt.MapClaims)
  24. claims["foo"] = "bar"
  25. claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
  26. token.Claims = claims
  27. // Sign and get the complete encoded token as a string
  28. tokenString, err := token.SignedString(signingKeyB)
  29. return tokenString, err
  30. }
  31. func parseToken(myToken string, myKey string) {
  32. token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
  33. return []byte(myKey), nil
  34. })
  35. if err == nil && token.Valid {
  36. fmt.Println("Your token is valid. I like your style.")
  37. } else {
  38. fmt.Println("This token is terrible! I cannot accept this.")
  39. }
  40. }