I'm trying to generate a token with a rsa key using the jwt-go package in golang.
Here there is a blog explaining how to do it but that code will always be validating all tokens because is using the public key stored in the server and is not obtaining it from the token. How do you put the complete public key in the token? I was trying this:
var secretKey, _ = rsa.GenerateKey(rand.Reader, 1024)
token := jwt.New(jwt.SigningMethodRS256)
token.Claims["username"] = "victorsamuelmd"
token.Claims["N"] = secretKey.PublicKey.N
token.Claims["E"] = secretKey.PublicKey.E
tokenString, err := token.SignedString(secretKey)
nt, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
// here I need to recover the public key from the token
// but N is a big.Int and the token stores N as int64
})
Sorry about my english. Thanks.
I think storing the public key in the claims is not good idea because we can verify the JWT with that key technically, but it means it is not a signed JWT anymore. If anyone can generate the JWT with their own private key and storing the public key in JWT, we cannot sure who is signer.
Anyway, you can convert the public key into PEM format which is just a string, and store it in claims. In client side, you can also simply parse it again into public key format. The sample code is below:
privateKey, _ := rsa.GenerateKey(rand.Reader, 1024)
bytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
pem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: bytes,
})
claim["publickey"] = string(pem)
and
pem := []byte(claims["publickey"].(string))
return jwt.ParseRSAPublicKeyFromPEM(pem)
jwt
is dgrijalva's jwt-go.