Is it possible to DI service in JwtSecurityTokenHandler
?
I am following herostwist's answer to modify the JwtTokenAuthenicaiton
in my code.
I have the following two, JwtSecurityTokenHandler
and IPostConfigureOptions<JwtBearerOptions>
:
public class CustomJwtBearerOptionsPostConfigureOptions
: IPostConfigureOptions<JwtBearerOptions>
{
private readonly RevokableJwtSecurityTokenHandler _revokableJwtSecurityTokenHandler;
public CustomJwtBearerOptionsPostConfigureOptions(
RevokableJwtSecurityTokenHandler revokableJwtSecurityTokenHandler)
{
_revokableJwtSecurityTokenHandler = revokableJwtSecurityTokenHandler;
}
public void PostConfigure(string name, JwtBearerOptions options)
{
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(_revokableJwtSecurityTokenHandler);
}
}
And:
public class RevokableJwtSecurityTokenHandler : JwtSecurityTokenHandler
{
//this DI has issue
private readyonly ApplicationDbContext _context;
public RevokableJwtSecurityTokenHandler(ApplicationDbContext context)
{
_context=context
}
public override ClaimsPrincipal ValidateToken(
string token, TokenValidationParameters validationParameters,
out SecurityToken validatedToken)
{
var claimsPrincipal =
base.ValidateToken(token, validationParameters, out validatedToken);
var claim = claimsPrincipal.FindFirst(JwtRegisteredClaimNames.Jti);
if (claim?.ValueType == ClaimValueTypes.String)
{
}
return claimsPrincipal;
}
}
I have the following in Startup.cs. It works for Singleton when the JwtSecurityTokenHandler doesn't have any DI. I wanted to inject ApplicationDBContext from Entity Framework. I tried with Transient and somehow I still getting the " Cannot consume scoped service" error.
services.AddTransient<RevokableJwtSecurityTokenHandler>();
services.AddTransient<IPostConfigureOptions<JwtBearerOptions>,
CustomJwtBearerOptionsPostConfigureOptions>();
Error:
AggregateException: Some services are not able to be constructed Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler': Cannot consume scoped service 'TestAPI.Data.ApplicationDbContext' from singleton