Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, May 13, 2024

Create and Parse JWT in GO



 


In this post we will review how to create and parse JWT in GO.


We use the "user" claim to specify the user. We create a signed JWT, and then parse it back to get the user from the JWT.


package jwtparsing

import (
"fmt"
"github.com/golang-jwt/jwt"
"testing"
"time"
)

const userClaim = "user"

func TestValidation(t *testing.T) {
signedToken := createJwtToken("myUser1")
fmt.Printf("token is: %v\n", signedToken)

user := parseJwtToken(signedToken)
fmt.Printf("user is: %v\n", user)
}


To create a JWT we should use a secret know only at the server side. The JWT is based on a specific signing method that should be supported on the client side as well.


func createJwtToken(
user string,
) string {
var secretKey = []byte("secret-key")

token := jwt.NewWithClaims(
jwt.SigningMethodHS256,
jwt.MapClaims{
userClaim: user,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})

signedToken, err := token.SignedString(secretKey)
if err != nil {
panic(err)
}
return signedToken
}


In this case we choose to parse the JWT without verifying it. It is important to understand the content of the JWT is not encrypted by only signed, hence we can parse it anywhere we want, without verification of the signature. This is ok only if we know that someone had already previously verified it, otherwise our system is broken.


func parseJwtToken(
signedToken string,
) string {
var jwtParser jwt.Parser
claims := jwt.MapClaims{}
_, _, err := jwtParser.ParseUnverified(signedToken, claims)
if err != nil {
panic(err)
}
jwtValue := claims[userClaim]
user, ok := jwtValue.(string)
if !ok {
panic("convert claim failed")
}

return user
}


The output of the test is:


=== RUN   TestValidation
token is: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTU2NzA3NDcsInVzZXIiOiJteVVzZXIxIn0.ynQLZ47Eup60OgkE0vbOtvii1g3MVSv4MxnvEE4Cv1U
user is: myUser1
--- PASS: TestValidation (0.00s)






No comments:

Post a Comment