TBD54566975 / web5-go

Apache License 2.0
10 stars 6 forks source link

Add jwt.Parse() Function #25

Closed KendallWeihe closed 6 months ago

KendallWeihe commented 7 months ago

Originally from this PR

  1. Create a new type JWT which includes both the jws.Header and jwt.Claims
  2. Take in a full signed JWT as input
  3. Run jwt.Verify()
  4. Parse out the header and claims parts
  5. Decode the base64 URL encoded header and claims
  6. Return both the decoded header and claims

Motivation

Rather than having the developer first do this...

parts := strings.Split(signedJwt, ".")
// todo error handle
base64UrlEncodedHeader := parts[0]
base64UrlEncodedClaims := parts[1]

...we may want to embed that in a function, as well as also executing a call to jwt.Verify(). I originally had the idea that we could create a function like this...

type JWT struct {
    Header jws.Header
    Claims jwt.Claims
}

func ParseJWT(signedJwt string) (JWT, error) {
    verified, err := jwt.Verify(signedJwt)
    if err != nil {
        // TODO handle error
    }
    if !verified {
        // TODO handle error
    }

    parts := strings.Split(signedJwt, ".")
    if len(parts) != 3 {
        // TODO handle error
    }

    base64UrlEncodedHeader := parts[0]
    base64UrlEncodedClaims := parts[1]
    // TODO check if base64UrlEncodedHeader & base64UrlEncodedClaims are proper base64 URL encoded strings?

    header, err := jws.DecodeJWSHeader(base64UrlEncodedHeader)
    if err != nil {
        // TODO handle error
    }

    claims, err := jwt.DecodeJWTClaims(base64UrlEncodedClaims)
    if err != nil {
        // TODO handle error
    }

    return JWT{Header: header, Claims: claims}, nil
}
mistermoe commented 6 months ago

good idea @KendallWeihe ! i think we can have jwt.Parse return a ParsedJWT which is a struct that:

we can also keep jwt.Verify as a conveniece which just calls internally Parse and then parsedJWT.Verify().

q4u: does Parse simply decode? or does it also check for things whether exp has passed? i vote for decode in which case might make the most sense to call it jwt.Decode

KendallWeihe commented 6 months ago

@mistermoe yeah I agree with all of that. Started fleshing it out here earlier, but there are implications with the jws package which relies on the string JWT... so I'm still thinking through how it'll fit together.