简体   繁体   中英

Golang package jwt-go with rsa key. How to put the public key and how to get it from the token?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM