3

I have developed the following method, which should enable token-based authentication (jwt). An asynchronous process should be used to generate the token.

The source code seems to work up to and including the generation of the signed token. I encountered an issue when querying the token with ParseWithClaims. Can someone help please?

package controllers

import (
    "crypto/rand"
    rsaKeys "crypto/rsa"
    "fmt"

    jwtgo "github.com/dgrijalva/jwt-go"
    "github.com/gofiber/fiber"
)

func Login(c *fiber.Ctx) error {
    
    type TestClaims struct {
        HAPP string `json:"happ"`
        jwtgo.StandardClaims
    }

    currentPrivateKey, err := rsaKeys.GenerateKey(rand.Reader, 512)

    claims := TestClaims{
        "owa",
        jwtgo.StandardClaims{
            Issuer:    "test",
            ExpiresAt: 15000,
        },
    }

    token := jwtgo.NewWithClaims(jwtgo.SigningMethodRS256, claims)

    tokenSigned, err := token.SignedString(currentPrivateKey)
    if err != nil {
        fmt.Printf("Failed to sign in account %v", err)
    }

    //Issue is in this statement
    _, errTest := jwtgo.ParseWithClaims(tokenSigned, &TestClaims{"owa", jwtgo.StandardClaims{}}, func(token *jwtgo.Token) (interface{}, error) {
        return currentPrivateKey, nil
    })

    if errTest != nil {
        fmt.Printf("Error Message: %v", errTest) //Does throw error: key is of invalid type
    }

    return c.JSON(fiber.Map{
        "message": "success",
    })
}

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Markus Bach
  • 763
  • 1
  • 8
  • 24

1 Answers1

3

To validate the JWT you need the public key, specifically ParseWithClaims expects a key of type *rsa.PublicKey.

You can get it from the private key with PrivateKey.Public:

tok, err := jwtgo.ParseWithClaims(tokenSigned, &TestClaims{"owa", jwtgo.StandardClaims{}}, func(token *jwtgo.Token) (interface{}, error) {
    return currentPrivateKey.Public(), nil
})

Please note that dgrijalva/jwt-go is unmaintained. If you can, switch to the community fork golang-jwt/jwt, which includes critical security fixes.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
  • Thanks for the answer and thanks for the information. Does it take a lot of effort to make the changes? – Markus Bach Jul 22 '21 at 09:33
  • @MarkusBach no I don't think so, the community fork's first version should be compatible with the original, except for some critical fixes which were an absolute must (and you want to fix those in your code anyway, in case...). However, personally, I switched all my production systems to `lestrrat-go/jwx` – blackgreen Jul 22 '21 at 09:35