Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a public key and a JWT, how do I check if it's valid in Go?

Tags:

go

jwt

jwt-go

I have a public key from my identity provider

-----BEGIN PUBLIC KEY-----
THIS
-----END PUBLIC KEY-----

And a JWT token from my client.

How do I check the token against the key? I'm having difficulty with jwt-go because the Parse function takes the token string and a getKey function.

Not sure how exactly to proceed

like image 697
David Alsh Avatar asked Aug 14 '18 05:08

David Alsh


2 Answers

The token was signed by RSA algorithm that uses a private key to sign and a public key to verify. Store your public key to the files system and use jwt.SigningMethodRS256.Verify() to verify. As the following snippet:

package main

import (
    "fmt"
    "strings"
    "log"
    "io/ioutil"
    jwt "github.com/dgrijalva/jwt-go"
)

func main() {
    publicKeyPath := "~/public_key.key"
    token := "your_jwt_token_here"

    if isValid, err := verifyToken(token, publicKeyPath)
    if err != nil {
        log.Fatal(err)
    }

    if isValid {
        fmt.Println("The token is valid")
    } else {
        fmt.Println("The token is invalid")
    }
}

func verifyToken(token, publicKeyPath string) (bool, error) {
    keyData, err := ioutil.ReadFile(publicKeyPath)
    if err != nil {
        return false, err
    }
    key, err := jwt.ParseRSAPublicKeyFromPEM(keyData)
    if err != nil {
        return false, err
    }

    parts := strings.Split(token, ".")
    err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], key)
    if err != nil {
        return false, nil
    }
    return true, nil
}
like image 175
Nguyen Dang Minh Avatar answered Oct 15 '22 11:10

Nguyen Dang Minh


Using jwt-go, you can do this

token, err := p.Parse(IDToken, func(*jwt.Token) (interface{}, error) {
    return []byte(signingKey), nil
})

And it will verify the token against the key.

Quoting the documentation,

type Keyfunc func(*Token) (interface{}, error)

Parse methods use this callback function to supply the key for verification. The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as kid) to identify which key to use.

like image 31
Ullaakut Avatar answered Oct 15 '22 10:10

Ullaakut