Created
March 22, 2021 20:31
-
-
Save watfordgnf/771f882bab8233e4def8345ad89c52ad to your computer and use it in GitHub Desktop.
Minimal reproduction for https://github.com/uruk-project/Jwt/issues/557
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Security.Cryptography; | |
using System.Security.Cryptography.X509Certificates; | |
using JsonWebToken; | |
using Xunit; | |
namespace JwtIssues | |
{ | |
public class JwtIssue557Test | |
{ | |
// SUCCEEDS | |
[Fact] | |
public void AlgInJWKS() => Test(RsaJwk.GenerateKey(2048, true, SignatureAlgorithm.RsaSha256)); | |
// FAILS | |
[Fact] | |
public void AlgNotInJWKS() => Test(CreateFromX509()); | |
private static void Test(Jwk jwk) | |
{ | |
JwtWriter writer = new JwtWriter(); | |
var jws = Build(jwk); | |
var token = writer.WriteTokenString(jws); | |
var reader = new JwtReader(); | |
var result = reader.TryReadToken(token, Policy(new Jwks(jwk))); | |
Assert.True(result.Succedeed); | |
} | |
private static TokenValidationPolicy Policy(Jwks jwks) | |
=> new TokenValidationPolicyBuilder() | |
.RequireIssuer("issuer") | |
.RequireAudience("audience") | |
.RequireSignature(jwks) | |
.Build(); | |
private static JwsDescriptor Build(Jwk key) | |
=> new JwsDescriptor | |
{ | |
KeyId = key.Kid, | |
Algorithm = SignatureAlgorithm.RsaSha256, | |
SigningKey = key, | |
Audience = "audience", | |
Issuer = "issuer", | |
IssuedAt = DateTime.UtcNow, | |
ExpirationTime = DateTime.UtcNow.AddHours(1), | |
JwtId = "abc", | |
Subject = "abc", | |
}; | |
private static Jwk CreateFromX509() | |
{ | |
using var rsaKey = RSA.Create(2048); | |
var csr = new CertificateRequest($"cn={Guid.NewGuid()}", rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); | |
csr.CertificateExtensions.Add( | |
new X509BasicConstraintsExtension(false, false, 0, false)); | |
csr.CertificateExtensions.Add( | |
new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation, false)); | |
csr.CertificateExtensions.Add( | |
new X509SubjectKeyIdentifierExtension(csr.PublicKey, false)); | |
var cert = csr.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); | |
return Jwk.FromX509Certificate(cert, true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment