Skip to content

Instantly share code, notes, and snippets.

@carlfranz
Created February 23, 2019 12:10
Show Gist options
  • Select an option

  • Save carlfranz/16c9865bb653c5ec8a55687268f1d830 to your computer and use it in GitHub Desktop.

Select an option

Save carlfranz/16c9865bb653c5ec8a55687268f1d830 to your computer and use it in GitHub Desktop.
Golang JWT token verification with jose-jwt
package main
import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
func main() {
tokenString, err := ioutil.ReadFile("accesstoken.txt")
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening accesstoken.txt\n")
}
certBuffer, err := ioutil.ReadFile("cert.pem")
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening cert.pem\n")
}
publicKey, err := LoadPublicKey(certBuffer)
if err != nil {
log.Fatalf("failed to load PEM :%+v", err)
}
parsed, err := jwt.ParseSigned(string(tokenString))
if err != nil {
log.Fatalf("failed to parse JWT:%+v", err)
}
allClaims := make(map[string]interface{})
err = parsed.Claims(publicKey, &allClaims)
if err != nil {
log.Fatalf("Failed to get claims JWT: %+v", err)
}
fmt.Print(allClaims["exp"])
}
// LoadPublicKey is a function from jose-util
func LoadPublicKey(data []byte) (interface{}, error) {
input := data
block, _ := pem.Decode(data)
if block != nil {
input = block.Bytes
}
// Try to load SubjectPublicKeyInfo
pub, err0 := x509.ParsePKIXPublicKey(input)
if err0 == nil {
return pub, nil
}
cert, err1 := x509.ParseCertificate(input)
if err1 == nil {
return cert.PublicKey, nil
}
jwk, err2 := LoadJSONWebKey(data, true)
if err2 == nil {
return jwk, nil
}
return nil, fmt.Errorf("square/go-jose: parse error, got '%s', '%s' and '%s'", err0, err1, err2)
}
// LoadJSONWebKey is another function from jose-util
func LoadJSONWebKey(json []byte, pub bool) (*jose.JSONWebKey, error) {
var jwk jose.JSONWebKey
err := jwk.UnmarshalJSON(json)
if err != nil {
return nil, err
}
if !jwk.Valid() {
return nil, errors.New("invalid JWK key")
}
if jwk.IsPublic() != pub {
return nil, errors.New("priv/pub JWK key mismatch")
}
return &jwk, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment