2

I'm trying to generate a jwt token using ECDSA ES256 method and use it for api request, I've been able to generate a []publicPEM and []privatePEM from an *ecdsa.PrivateKey, I used the *ecdsa.PrivateKey to get the jwt token


// Secret is revoked
JWT_SECRET := `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIGaozMA951amsyyAjz/C3FUhdspS1Kqi3s5EdbJeop0boAoGCCqGSM49
AwEHoUQDQgAEPvB35tXsy4P4ZKpH3jAGGWA4ZVOnQsiLPBrWfjk76UXnrXqZO5LW
EHK9AyZbafH3s+QwFG5zIrv8gf6Fx5qItw==
-----END EC PRIVATE KEY-----`

block, _ := pem.Decode([]byte(JWT_SECRET))
if privKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
    log.Fatal(err)
}
....
// Generate token
uAccessToken := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
        "iss":         "issuer",
        "sub":         "access token",
        "exp":         time.Now().Add(time.Minute * 20).Unix(),
})
if tA.AccessToken, err = uAccessToken.SignedString(privKey); err != nil {
    return nil, err
}

/// Parse token

token, err := jwt.Parse(tA.AccessToken, func(t *jwt.Token) (interface{}, error) {
    log.Println("%s", t.Valid) // false
    return privKey, nil
})
if err != nil {
    log.Fatal(err) // Key is of invalid type
}

From what I understood from the doc, KeyFunc should return the key used in signing token for HS256 []byte worked but *ecdsa.PrivateKey is not working in this case.

I can't get pass this point to verify the token :(

Don't know what I'm doing wrong, still a newbie in golang

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Epikoder
  • 79
  • 7
  • 1
    I think you should `jwt.ParseECPrivateKeyFromPEM` instead or `x509.ParseECPrivateKey`. And I also think you should return a public key when you parse. – zerkms Jul 29 '21 at 00:53
  • https://github.com/dgrijalva/jwt-go/blob/008eba19055c071829e8317937b39845a9d2019b/ecdsa.go#L70 – zerkms Jul 29 '21 at 00:57
  • @zerkms https://github.com/dgrijalva/jwt-go/blob/008eba19055c071829e8317937b39845a9d2019b/ecdsa.go#L104 from this line it's using private key in the sign function, does that mean I need to sign with private key and use public key when parsing the token.. thank you :) – Epikoder Jul 29 '21 at 01:15
  • That's right: you sign with a private key, and verify with a public key. – zerkms Jul 29 '21 at 02:11
  • 1
    Related: https://stackoverflow.com/questions/68481150 – blackgreen Jul 29 '21 at 08:12
  • Also don't use `dgrijalva/jwt-go` it's unmaintained and has critical security bugs. Use the community fork, or switch to another package. I explained more [here](https://stackoverflow.com/a/68159566/4108803) – blackgreen Jul 29 '21 at 08:13
  • Yes I'm aware of that – Epikoder Jul 29 '21 at 18:00

0 Answers0