mjwt/verifier.go

51 lines
1.3 KiB
Go
Raw Normal View History

2022-12-04 13:42:35 +00:00
package mjwt
import (
"crypto/rsa"
"github.com/1f349/rsa-helper/rsapublic"
2022-12-04 13:42:35 +00:00
"github.com/golang-jwt/jwt/v4"
)
2023-06-19 11:40:28 +01:00
// defaultMJwtVerifier implements Verifier and uses a rsa.PublicKey to validate
2023-06-18 18:09:49 +01:00
// 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) {
// read key
pub, err := rsapublic.Read(file)
2022-12-04 13:42:35 +00:00
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()
}
func (d *defaultMJwtVerifier) PublicKey() *rsa.PublicKey { return d.pub }