Add test for NewMJwtVerifierFromFile

This commit is contained in:
Melon 2023-06-19 11:40:28 +01:00
parent 8806e30591
commit 9ea1842360
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
3 changed files with 35 additions and 5 deletions

View File

@ -12,7 +12,7 @@ import (
type testClaims struct{ TestValue string }
func (t testClaims) Valid() error {
if t.TestValue != "hello" {
if t.TestValue != "hello" && t.TestValue != "world" {
return fmt.Errorf("TestValue should be hello")
}
return nil

View File

@ -5,13 +5,10 @@ import (
"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")
// defaultMJwtVerifier implements Verifier and uses an rsa.PublicKey to validate
// defaultMJwtVerifier implements Verifier and uses a rsa.PublicKey to validate
// MJWT tokens
type defaultMJwtVerifier struct {
pub *rsa.PublicKey

33
verifier_test.go Normal file
View File

@ -0,0 +1,33 @@
package mjwt
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/stretchr/testify/assert"
"os"
"testing"
"time"
)
func TestNewMJwtVerifierFromFile(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
assert.NoError(t, err)
s := NewMJwtSigner("mjwt.test", key)
token, err := s.GenerateJwt("1", "test", 10*time.Minute, testClaims{TestValue: "world"})
assert.NoError(t, err)
b := pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(&key.PublicKey)})
temp, err := os.CreateTemp("", "this-is-a-test-file.pem")
assert.NoError(t, err)
_, err = temp.Write(b)
assert.NoError(t, err)
file, err := NewMJwtVerifierFromFile(temp.Name())
assert.NoError(t, err)
_, _, err = ExtractClaims[testClaims](file, token)
assert.NoError(t, err)
err = os.Remove(temp.Name())
assert.NoError(t, err)
}