Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "os"
- "time"
- "github.com/golang-jwt/jwt/v5"
- )
- type CustomClaim struct {
- Id string `json:"id"`
- jwt.RegisteredClaims
- }
- func generateToken(id string) string {
- key, err := os.ReadFile("./app.rsa")
- if err != nil {
- panic(err)
- }
- private_key, err := jwt.ParseRSAPrivateKeyFromPEM(key)
- if err != nil {
- panic(err)
- }
- claim := CustomClaim{
- Id: id,
- RegisteredClaims: jwt.RegisteredClaims{
- IssuedAt: jwt.NewNumericDate(time.Now()),
- ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)),
- },
- }
- token := jwt.NewWithClaims(jwt.SigningMethodRS256, &claim)
- ss, err := token.SignedString(private_key)
- if err != nil {
- panic(err)
- }
- return string(ss)
- }
- func ParseJwt(token string) CustomClaim {
- key, err := os.ReadFile("./app.rsa.pub")
- if err != nil {
- panic(err)
- }
- pub_key, err := jwt.ParseRSAPublicKeyFromPEM(key)
- claim, err := jwt.ParseWithClaims(token, &CustomClaim{}, func(t *jwt.Token) (interface{}, error) {
- if _, ok := t.Method.(*jwt.SigningMethodRSA); !ok {
- return nil, fmt.Errorf("Unexpected signing method: %v", t.Header["alg"])
- }
- return pub_key, nil
- })
- if err != nil {
- panic(err)
- }
- if parsed, ok := claim.Claims.(*CustomClaim); ok {
- return *parsed
- }
- panic("failed parsed")
- }
- func main() {
- token := generateToken("foo")
- fmt.Println(token)
- parsed := ParseJwt(token)
- fmt.Println("jwt id: ", parsed.ID)
- fmt.Println("issued at: ", parsed.IssuedAt)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement