aldikhan13

Custom JWT Method in Go Like JWT Javascript

Apr 17th, 2021 (edited)
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 2.35 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. // example usage
  6. func main() {
  7.  
  8.  userData := map[string]interface{}{"id": 1, "email": "restuwahyu13@zetmail.com", "github_name": "restuwahyu13"}
  9.   accessToken, err := util.Sign(userData, "JWT_SECRET", 1) // data -> secretkey env name -> expiredAt
  10.  
  11.  fmt.Println("my accessToken here", accessToken)
  12. }
  13.  
  14. package util
  15.  
  16. import (
  17.     "encoding/json"
  18.     "strings"
  19.     "time"
  20.  
  21.     "github.com/dgrijalva/jwt-go"
  22.     "github.com/gin-gonic/gin"
  23.     "github.com/sirupsen/logrus"
  24. )
  25.  
  26. // metadata for your jwt
  27. type MetaToken struct {
  28.     ID            int
  29.     Email         string
  30.     ExpiredAt     time.Time
  31.     Authorization bool
  32. }
  33.  
  34. type AccessToken struct {
  35.     Claims MetaToken
  36. }
  37.  
  38. func Sign(Data map[string]interface{}, SecrePublicKeyEnvName string, ExpiredAt time.Duration) (string, error) {
  39.  
  40.     expiredAt := time.Now().Add(time.Duration(time.Second) * ExpiredAt).Unix()
  41.  
  42.     jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)
  43.  
  44.     // metadata for your jwt
  45.     claims := jwt.MapClaims{}
  46.     claims["expiredAt"] = expiredAt
  47.     claims["authorization"] = true
  48.  
  49.     for i, v := range Data {
  50.         claims[i] = v
  51.     }
  52.  
  53.     to := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  54.     accessToken, err := to.SignedString([]byte(jwtSecretKey))
  55.  
  56.     if err != nil {
  57.         logrus.Error(err.Error())
  58.         return accessToken, err
  59.     }
  60.  
  61.     return accessToken, nil
  62. }
  63.  
  64. func VerifyTokenHeader(ctx *gin.Context, SecrePublicKeyEnvName string) (*jwt.Token, error) {
  65.     tokenHeader := ctx.GetHeader("Authorization")
  66.     accessToken := strings.SplitAfter(tokenHeader, "Bearer")[1]
  67.     jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)
  68.  
  69.     token, err := jwt.Parse(strings.Trim(accessToken, " "), func(token *jwt.Token) (interface{}, error) {
  70.         return []byte(jwtSecretKey), nil
  71.     })
  72.  
  73.     if err != nil {
  74.         logrus.Error(err.Error())
  75.         return nil, err
  76.     }
  77.  
  78.     return token, nil
  79. }
  80.  
  81. func VerifyToken(accessToken, SecrePublicKeyEnvName string) (*jwt.Token, error) {
  82.     jwtSecretKey := GodotEnv(SecrePublicKeyEnvName)
  83.  
  84.     token, err := jwt.Parse(accessToken, func(token *jwt.Token) (interface{}, error) {
  85.         return []byte(jwtSecretKey), nil
  86.     })
  87.  
  88.     if err != nil {
  89.         logrus.Error(err.Error())
  90.         return nil, err
  91.     }
  92.  
  93.     return token, nil
  94. }
  95.  
  96. func DecodeToken(accessToken *jwt.Token) AccessToken {
  97.     var token AccessToken
  98.     stringify, _ := json.Marshal(&accessToken)
  99.     json.Unmarshal([]byte(stringify), &token)
  100.  
  101.     return token
  102. }
Add Comment
Please, Sign In to add comment