jrpalma / jwt

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Helper functions or Utility function of extracting claims

natintosh opened this issue · comments

Hello @jrpalma thanks for the package. I don't know if you will like to but I think it would be great if this package has some functions that will enable me to decode token into various sections like Headers and Claims, so that I can unmarshal it. I am not sure if this already exists

Hi Natintosh,
There are Marshal and Unmarshal functions for both the Header and Claims. Take a look at this for example https://github.com/jrpalma/jwt/blob/master/header.go#L162

You can use those functions. Let me know if these functions fulfill your use cases or if you are looking for something different.

Regards,
Jose

Thanks, Jose I think I get it now. but it's just that I still need to decode the token before I can unmarshal it.

        
func GetClaims(token string) *jwt.Claims {
	claims := jwt.NewClaims()

	tokenArr := strings.Split(token, ".")

	if len(tokenArr) != 3 {
		return nil
	}

	claimsJSON, err := base64.RawURLEncoding.DecodeString(string(tokenArr[1]))

	if err != nil {
		return nil
	}
       
	err := claims.Unmarshal(claimsJSON)
       
	if err != nil {
		return nil
	}
       
	return claims
}

Hi Natintosh,
I see the problem in the snippet of code you posted. It is much simpler than that. If you look at the documentation, you can see that you can "Marshal" and "Unmarshal" with "Sign" and "Verify" respectively. https://github.com/jrpalma/jwt/blob/master/jwt.go#L55. The README.md provides clues on how to use it.

token := NewJWT()
token.Claims.Set("user", "jose")
token.Claims.Set("id", "12345666666")

base64JWT, signErr := token.Sign("secret")
if signErr != nil {
	return signerr
}
// Send to the client via header or cookie

// Verify the token's integrity, and unmarshall the header and claims in one shot.
verifyErr := token.Verify(base64JWT, "secret")
if verifyErr != nil {
	test.Errorf("Failed to verify token: %v", verifyErr)
}

Notice that Sign creates the base64 encoded token. You can send the token in a header or send it as a cookie to the client. Once the client sends it back for authentication, you can"Verify" the token which effectively "Unrmarshalls" the base64 encoded token into the header and claims.

I hope this helps.