Last active
November 17, 2023 20:05
-
-
Save mayankchoubey/6eda61dc209bdc8e72e10bd5237cd5f2 to your computer and use it in GitHub Desktop.
Go - JWT sign and verify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "io/ioutil" | |
| "github.com/golang-jwt/jwt" | |
| "strconv" | |
| "os" | |
| "time" | |
| "fmt" | |
| ) | |
| func main() { | |
| file, _ := ioutil.ReadFile("/Users/mayankc/Work/source/perfComparisons/testdata/emails.json") | |
| var emails []string | |
| _ = json.Unmarshal([]byte(file), &emails) | |
| var i = 1 | |
| var idx = 0 | |
| var jwtSecret = []byte(os.Getenv("JWT_SECRET")) | |
| var numIterationsStr = os.Args[1] | |
| var numIterations, _ = strconv.Atoi(numIterationsStr) | |
| var startTS int64 = 0 | |
| for { | |
| if i == 10000 { | |
| startTS = time.Now().UnixMilli() | |
| } | |
| email := emails[idx] | |
| currTS := time.Now().UnixMilli() | |
| token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ | |
| "sub": email, | |
| "iat": currTS, | |
| "exp": currTS + 2 * 60 * 60 * 1000, | |
| }) | |
| tokenString, _ := token.SignedString(jwtSecret) | |
| token2, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { | |
| return jwtSecret, nil | |
| }) | |
| claims, _ := token2.Claims.(jwt.MapClaims); | |
| if claims["sub"] != email { | |
| os.Exit(1) | |
| } | |
| idx++ | |
| if idx >= len(emails) { | |
| idx = 0 | |
| } | |
| i++ | |
| if i > numIterations { | |
| break | |
| } | |
| } | |
| var endTS = time.Now().UnixMilli() | |
| var diff = endTS - startTS | |
| fmt.Println(diff) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment