Skip to content

Instantly share code, notes, and snippets.

@arshamalh
Created June 10, 2022 21:57
Show Gist options
  • Save arshamalh/d81a8a049e48669183382002ee747c76 to your computer and use it in GitHub Desktop.
Save arshamalh/d81a8a049e48669183382002ee747c76 to your computer and use it in GitHub Desktop.
Golang JWT and intervals (using goroutines and channels)
package main
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
)
func main() {
access_token, _ := GenerateToken("test", time.Second*2, "secret")
ch, clearInterval := Interval(time.Second * 1)
for range ch {
jwt, err := ExtractTokenData(access_token, "secret")
if err != nil {
fmt.Println(err)
fmt.Printf("%+v\n", jwt.Subject)
clearInterval()
} else {
fmt.Println(jwt.Subject)
}
fmt.Println("------------------")
}
}
func Interval(d time.Duration) (chan bool, func()) {
ch := make(chan bool)
quit := make(chan bool)
cancel := func() { quit <- true }
go func() {
for {
time.Sleep(d)
select {
case ch <- true:
case <-quit:
close(ch)
}
}
}()
return ch, cancel
}
func GenerateToken(subject string, lifespan time.Duration, secret string) (string, error) {
payload := jwt.StandardClaims{
Subject: subject,
ExpiresAt: time.Now().Add(lifespan).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)
return token.SignedString([]byte(secret))
}
func ExtractTokenData(token string, secret string) (*jwt.StandardClaims, error) {
jwt_token, err := jwt.ParseWithClaims(
token, &jwt.StandardClaims{},
func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
},
)
payload := jwt_token.Claims.(*jwt.StandardClaims)
fmt.Println("is valid: ", jwt_token.Valid)
if err != nil {
return payload, err
} else if !jwt_token.Valid {
return payload, fmt.Errorf("invalid token")
}
return payload, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment