Advertisement
Guest User

jwt example

a guest
Sep 7th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.50 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "os"
  6.     "time"
  7.  
  8.     "github.com/golang-jwt/jwt/v5"
  9. )
  10.  
  11. type CustomClaim struct {
  12.     Id string `json:"id"`
  13.     jwt.RegisteredClaims
  14. }
  15.  
  16. func generateToken(id string) string {
  17.     key, err := os.ReadFile("./app.rsa")
  18.     if err != nil {
  19.         panic(err)
  20.     }
  21.  
  22.     private_key, err := jwt.ParseRSAPrivateKeyFromPEM(key)
  23.     if err != nil {
  24.         panic(err)
  25.     }
  26.  
  27.     claim := CustomClaim{
  28.         Id: id,
  29.         RegisteredClaims: jwt.RegisteredClaims{
  30.             IssuedAt:  jwt.NewNumericDate(time.Now()),
  31.             ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
  32.         },
  33.     }
  34.  
  35.     token := jwt.NewWithClaims(jwt.SigningMethodRS256, &claim)
  36.  
  37.     ss, err := token.SignedString(private_key)
  38.     if err != nil {
  39.         panic(err)
  40.     }
  41.  
  42.     return string(ss)
  43. }
  44.  
  45. func ParseJwt(token string) CustomClaim {
  46.     key, err := os.ReadFile("./app.rsa.pub")
  47.     if err != nil {
  48.         panic(err)
  49.     }
  50.  
  51.     pub_key, err := jwt.ParseRSAPublicKeyFromPEM(key)
  52.  
  53.     claim, err := jwt.ParseWithClaims(token, &CustomClaim{}, func(t *jwt.Token) (interface{}, error) {
  54.         if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
  55.             return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
  56.         }
  57.  
  58.         return pub_key, nil
  59.     })
  60.  
  61.     if err != nil {
  62.         panic(err)
  63.     }
  64.  
  65.     if parsed, ok := claim.Claims.(*CustomClaim); ok {
  66.         return *parsed
  67.     }
  68.  
  69.     panic("failed parsed")
  70. }
  71.  
  72. func main() {
  73.     token := generateToken("foo")
  74.  
  75.     fmt.Println(token)
  76.  
  77.     parsed := ParseJwt(token)
  78.  
  79.     fmt.Println("jwt id: ", parsed.ID)
  80.     fmt.Println("issued at: ", parsed.IssuedAt)
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement