0

I am trying to generate a JWT token using Go and I created the following function. I need to add the email address in jwt but as I do this I get an error saying key is of invalid type

func GenerateUserToken(expiryHours time.Duration, email string, secretKey string) (string, error) {
    // Create a new token object, specifying signing method and the claims
    // you would like it to contain.
    token := jwt.New(jwt.SigningMethodES256)
    claims := token.Claims.(jwt.MapClaims)
    claims["exp"] = time.Now().Add(time.Hour * expiryHours).Unix()
    claims["email"] = email

    tokenStr, err := token.SignedString([]byte(secretKey))
    if err != nil {
        return "", err
    }

    return tokenStr, nil
}

What could be the reason for this? What mistake am I making?

Grokify
  • 15,092
  • 6
  • 60
  • 81
Amanda
  • 2,013
  • 3
  • 24
  • 57

1 Answers1

1

JWT supports many signing algorithms, and that's a challenge for this particular API: depending on the signing algorithm, it expects to see a key matching that algorithm.

If you take a look at the API docs for this particular library:

https://godoc.org/github.com/dgrijalva/jwt-go

You'll see SigningMethodXXX types. These are signers selected by the signing method you pick. For ES256, it uses SigningMethodECDSA:

https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA

If you look at the Sign method docs, you'll see that it says:

For this signing method, key must be an ecdsa.PrivateKey struct

which you can parse from a PEM file using:

https://godoc.org/github.com/dgrijalva/jwt-go#ParseECPrivateKeyFromPEM

For example:

pk, err:= jwt.ParseECPrivateKeyFromPEM(pemData)
tokenStr, err := token.SignedString(pk)

This should give you a signed token with ES256.

So, you have to first figure out what kind of key you have. If you have a PEM encoding of a ECDSA key in a string, then use this method to parse it and pass the resulting private key to the signer.

If however you simply have a string secret key (like a password) and you'll share this secret key with the users of the JWT, then you can use a HMAC key. A HMAC key is simply a byte array secret that you share with your users so they can validate that the JWT was signed by you. Simply change the SigningMethod to one of the constants in:

https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC

Then, your code as it is will work with the exception that you have to change the signing method to something like jwt.New(jwt.SigningMethodHS256)

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59