JwtBuilder WithAlgorithmFactory and Encode doesn't work.
drusellers opened this issue · 4 comments
I just tried to use
var builder = JwtBuilder.Create()
.WithAlgorithmFactory(_myHardCodedFactory)
.AddHeader("kid", "the-kid")
.AddClaim("bob", "bill")
.Encode();
And I got the exception
System.ArgumentNullException : Value cannot be null. (Parameter 'algorithm')
at JWT.Algorithms.DelegateAlgorithmFactory..ctor(IJwtAlgorithm algorithm)
at JWT.JwtEncoder..ctor(IJwtAlgorithm algorithm, IJsonSerializer jsonSerializer, IBase64UrlEncoder urlEncoder)
at JWT.Builder.JwtBuilder.TryCreateEncoder()
at JWT.Builder.JwtBuilder.EnsureCanEncode()
at JWT.Builder.JwtBuilder.Encode()
...
Which surprised me because I gave the builder an algorithm factory to use, that will produce an algo if asked.
I also noticed that there aren't any tests that cover using the WithAlgorithmFactory
and not providing an WithAlgorithm
Does it make sense to allow this to work for encoding?
Library 9.1
Looking at the code:
jwt/src/JWT/Algorithms/DelegateAlgorithmFactory.cs
Lines 23 to 29 in 070389b
The only reason for the error is that _myHardCodedFactory
returns null
.
Can you make sure it doesn't? Post its code here, if possible. Let's take a look.
using JWT;
using JWT.Algorithms;
using JWT.Builder;
using NUnit.Framework;
public class JwtBuilderTest
{
[Test]
public void Fails()
{
var token = JwtBuilder.Create()
.AddClaim("A","B")
.WithSecret(new[]{"deadbeef"})
.WithAlgorithmFactory(new HardCodedFactory())
.Encode();
}
[Test]
public void Passes()
{
var token = JwtBuilder.Create()
.AddClaim("A","B")
.WithSecret(new[]{"deadbeef"})
.WithAlgorithm(new HMACSHA256Algorithm())
.Encode();
}
class HardCodedFactory : IAlgorithmFactory
{
public IJwtAlgorithm Create(JwtDecoderContext context)
{
return new HMACSHA256Algorithm();
}
}
}
Sorry for the bug and thanks for reporting it. Fixed and published to NuGet as 10.0.0-beta2
@abatishchev not a problem at all. It's a team effort. TY for being so responsive.