mjwt/verifier.go

63 lines
1.5 KiB
Go
Raw Normal View History

2022-12-04 13:42:35 +00:00
package mjwt
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors"
"os"
)
var ErrCannotGenerateMJwtToken = errors.New("cannot generate mjwt token with verifier")
2023-06-18 18:09:49 +01:00
// defaultMJwtVerifier implements Verifier and uses an rsa.PublicKey to validate
// MJWT tokens
2022-12-04 13:42:35 +00:00
type defaultMJwtVerifier struct {
pub *rsa.PublicKey
}
var _ Verifier = &defaultMJwtVerifier{}
2022-12-04 13:42:35 +00:00
2023-06-18 18:09:49 +01:00
// NewMJwtVerifier creates a new defaultMJwtVerifier using the rsa.PublicKey
func NewMJwtVerifier(key *rsa.PublicKey) Verifier {
2022-12-04 13:42:35 +00:00
return newMJwtVerifier(key)
}
func newMJwtVerifier(key *rsa.PublicKey) *defaultMJwtVerifier {
return &defaultMJwtVerifier{pub: key}
}
2023-06-18 18:09:49 +01:00
// NewMJwtVerifierFromFile creates a new defaultMJwtVerifier using the path of a
// rsa.PublicKey file
func NewMJwtVerifierFromFile(file string) (Verifier, error) {
2023-06-18 18:09:49 +01:00
// read file
2022-12-04 13:42:35 +00:00
f, err := os.ReadFile(file)
if err != nil {
return nil, err
}
2023-06-18 18:09:49 +01:00
// decode pem block
2022-12-04 13:42:35 +00:00
block, _ := pem.Decode(f)
2023-06-18 18:09:49 +01:00
// parse public key from pem block
2022-12-04 13:42:35 +00:00
pub, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, err
}
2023-06-18 18:09:49 +01:00
// create verifier using rsa.PublicKey
return NewMJwtVerifier(pub), nil
2022-12-09 13:22:10 +00:00
}
2023-06-18 18:09:49 +01:00
// VerifyJwt validates and parses MJWT tokens and returns the claims
2022-12-04 13:42:35 +00:00
func (d *defaultMJwtVerifier) VerifyJwt(token string, claims baseTypeClaim) (*jwt.Token, error) {
withClaims, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return d.pub, nil
})
if err != nil {
return nil, err
}
return withClaims, claims.Valid()
}