Using `errors.As` to check for validation errors

This commit is contained in:
Christian Banse 2021-11-29 21:23:48 +01:00
parent a725c1f60c
commit 957802ced4
2 changed files with 21 additions and 12 deletions

View File

@ -1,6 +1,7 @@
package jwt_test
import (
"errors"
"fmt"
"time"
@ -94,16 +95,22 @@ func ExampleParseWithClaims_customClaimsType() {
// An example of parsing the error types using bitfield checks
func ExampleParse_errorChecking() {
// Token from another example. This token is expired
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
var (
token *jwt.Token
ve *jwt.ValidationError
err error
)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Token from another example. This token is expired
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
token, err = jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("AllYourBase"), nil
})
if token.Valid {
fmt.Println("You look nice today")
} else if ve, ok := err.(*jwt.ValidationError); ok {
} else if errors.As(err, &ve) {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
fmt.Println("That's not even a token")
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {

View File

@ -4,6 +4,7 @@ import (
"crypto"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"reflect"
"testing"
@ -325,6 +326,7 @@ func TestParser_Parse(t *testing.T) {
// Parse the token
var token *jwt.Token
var ve *jwt.ValidationError
var err error
var parser = data.parser
if parser == nil {
@ -361,8 +363,7 @@ func TestParser_Parse(t *testing.T) {
if err == nil {
t.Errorf("[%v] Expecting error. Didn't get one.", data.name)
} else {
ve := err.(*jwt.ValidationError)
if errors.As(err, &ve) {
// compare the bitfield part of the error
if e := ve.Errors; e != data.errors {
t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors)
@ -373,6 +374,7 @@ func TestParser_Parse(t *testing.T) {
}
}
}
}
if data.valid {
if token.Signature == "" {
t.Errorf("[%v] Signature is left unpopulated after parsing", data.name)