JWT authentication in Go

Verify JWT tokens in Go by parsing an X.509 certificate to extract the public key and using the golang-jwt library to validate the signature.

Use the golang-jwt/jwt library to parse and verify JWT tokens against a public key derived from your X.509 certificate. Decode the PEM certificate, parse it with x509.ParseCertificate, extract the public key, and pass it to jwt.Parse with the RS256 signing method.

import (
	"crypto/x509"
	"encoding/pem"
	"github.com/golang-jwt/jwt/v5"
)

func verifyJWT(tokenString string, certPEM string) (*jwt.Token, error) {
	block, _ := pem.Decode([]byte(certPEM))
	if block == nil {
		return nil, fmt.Errorf("failed to decode PEM")
	}
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return nil, err
	}

	return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return cert.PublicKey, nil
	})
}