2022-12-04 13:42:35 +00:00
|
|
|
package mjwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rsa"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-06-18 18:09:49 +01:00
|
|
|
// defaultMJwtSigner implements Signer and uses an rsa.PrivateKey and issuer name
|
|
|
|
// to generate MJWT tokens
|
2022-12-04 13:42:35 +00:00
|
|
|
type defaultMJwtSigner struct {
|
|
|
|
issuer string
|
|
|
|
key *rsa.PrivateKey
|
|
|
|
verify *defaultMJwtVerifier
|
|
|
|
}
|
|
|
|
|
2023-06-18 13:03:41 +01:00
|
|
|
var _ Signer = &defaultMJwtSigner{}
|
2022-12-04 13:42:35 +00:00
|
|
|
|
2023-06-18 18:09:49 +01:00
|
|
|
// NewMJwtSigner creates a new defaultMJwtSigner using the issuer name and rsa.PrivateKey
|
2023-06-18 13:03:41 +01:00
|
|
|
func NewMJwtSigner(issuer string, key *rsa.PrivateKey) Signer {
|
2022-12-04 13:42:35 +00:00
|
|
|
return &defaultMJwtSigner{
|
|
|
|
issuer: issuer,
|
|
|
|
key: key,
|
|
|
|
verify: newMJwtVerifier(&key.PublicKey),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-18 18:09:49 +01:00
|
|
|
// Issuer returns the name of the issuer
|
2022-12-04 13:42:35 +00:00
|
|
|
func (d *defaultMJwtSigner) Issuer() string { return d.issuer }
|
|
|
|
|
2023-06-18 18:09:49 +01:00
|
|
|
// GenerateJwt generates and returns a JWT string using the sub, id, duration and claims
|
2022-12-04 13:42:35 +00:00
|
|
|
func (d *defaultMJwtSigner) GenerateJwt(sub, id string, dur time.Duration, claims Claims) (string, error) {
|
2022-12-09 12:53:36 +00:00
|
|
|
return d.SignJwt(wrapClaims[Claims](d, sub, id, dur, claims))
|
|
|
|
}
|
|
|
|
|
2023-06-18 18:09:49 +01:00
|
|
|
// SignJwt signs a jwt.Claims compatible struct, this is used internally by
|
|
|
|
// GenerateJwt but is available for signing custom structs
|
2022-12-09 12:53:36 +00:00
|
|
|
func (d *defaultMJwtSigner) SignJwt(wrapped jwt.Claims) (string, error) {
|
2022-12-04 13:42:35 +00:00
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodRS512, wrapped)
|
|
|
|
return token.SignedString(d.key)
|
|
|
|
}
|
|
|
|
|
2023-06-18 18:09:49 +01:00
|
|
|
// VerifyJwt validates and parses MJWT tokens see defaultMJwtVerifier.VerifyJwt()
|
2022-12-04 13:42:35 +00:00
|
|
|
func (d *defaultMJwtSigner) VerifyJwt(token string, claims baseTypeClaim) (*jwt.Token, error) {
|
|
|
|
return d.verify.VerifyJwt(token, claims)
|
|
|
|
}
|