Reputation: 833
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",
})
}
Upvotes: 3
Views: 5541
Reputation: 45081
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.
Upvotes: 4