jwt icon indicating copy to clipboard operation
jwt copied to clipboard

Add Claim Field Validation

Open syke99 opened this issue 2 years ago • 0 comments

While this library does provide methods for checking the signature (such as HMCACheck(<token>, <secret>)) and for checking that the token hasn't expired (*Claims.Valid(time.Time)), it doesn't provide validators for validating each claim in the JWT payload. This PR adds the ability to create a validator for each field to then be used along with the Claims in ValidatePayloadClaims.

As an example:


// Create your field validators. For all minus the TimeFieldValidator, just pass in the expected
// results. For the TimeFieldValidator, pass in the time that all time fields must be valid for. (Does
// not have to be time.Now())
issValidator := jwt.IssuerValidator("testIssuer")
audValidator := jwt.AudiencesValidator([]string{"testAudienceOne", "testAudienceTwo"})
subValidator := jwt.SubjectValidator(strconv.Itoa(1234))
timeValidator := jwt.TimeFieldValidator(time.Now())
idValidator := jwt.IdValidator(strconv.Itoa(5678))

// Not only are there validators for the Registered claims, but there is also a validator for custom claims.
// Just pass in the expected value, and the name of the custom claim field.
customFieldValidator  := jwt.CustomClaimValidator("expectedCustomFieldValue", "customClaimFieldName")

// Pass in the token's claims and your field validators. tokenClaims is *Claims from the created token
err = jwt.ValidatePayloadClaims(tokenClaims, issValidator, audValidator, subValidator, timeValidator, idValidator, customFieldValidator)

syke99 avatar Aug 03 '22 21:08 syke99