2022-12-04 13:42:35 +00:00
|
|
|
package mjwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rsa"
|
2024-06-08 15:02:49 +01:00
|
|
|
"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
|
|
|
|
}
|
|
|
|
|
2023-06-18 13:03:41 +01:00
|
|
|
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
|
2023-06-18 13:03:41 +01:00
|
|
|
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
|
2023-06-18 13:03:41 +01:00
|
|
|
func NewMJwtVerifierFromFile(file string) (Verifier, error) {
|
2024-06-08 15:02:49 +01:00
|
|
|
// 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()
|
|
|
|
}
|
2023-10-25 17:37:55 +01:00
|
|
|
|
|
|
|
func (d *defaultMJwtVerifier) PublicKey() *rsa.PublicKey { return d.pub }
|