简体   繁体   中英

how to get Jwt.IssuerSigningKey using Mediator in Program.cs?

I'm moveing JwtAuthManager to JwtAuth to use Mediator calls to my DB.
everything for [AllowAnonymous] is working fine.
anything with [Authorize] is of course broken:
Bearer error="invalid_token",error_description="The signature key was not found"
Because i deleted the jwtTokenConfig.Secret
I want to add await _mediator.Send(new SecretCommand()); to the Program.cs, But i can't inject Mediator there.

code:

Program.cs

var jwtTokenConfig = builder.Configuration.GetSection("jwtTokenConfig").Get<JwtTokenConfig>();
builder.Services.AddSingleton(jwtTokenConfig);
builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = true;
    x.SaveToken = true;
    try
    {
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtTokenConfig.Issuer,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenConfig.Secret)),
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1)
        };
    }
    catch (global::System.Exception)
    {

    }

});

builder.Services.AddSingleton<DataAccessLibrary.Executs.Auth.IJwtAuth, DataAccessLibrary.Executs.Auth.JwtAuth>();
builder.Services.AddSingleton<IJwtAuthManager, JwtAuthManager>();
builder.Services.AddHostedService<JwtRefreshTokenCache>();
builder.Services.AddScoped<IUserService, UserService>();

builder.Services.AddSingleton<IUserAuthAcsess, UserAuthAcsess>();
builder.Services.AddSingleton<IJwtAuth, JwtAuth>();
builder.Services.AddMediatR(typeof(MyServer.ServerBace).GetTypeInfo().Assembly);
builder.Services.AddMediatR(typeof(DataAccessEntryPoint).GetTypeInfo().Assembly);


JwtAuth.cs

 public interface IJwtAuth
    {
        Task<Response> RemoveRefreshTokenByUserName(string UserName, string IpAddress);
        Task<Response<(ClaimsPrincipal, JwtSecurityToken)>> DecodeJwtToken(string Token);
        Task<Response<JwtAuthResult>> GenerateTokens(string UserName, Claim[] claims, DateTime now);
        Task<Response<JwtAuthResult>> RefreshToken(string RefreshToken, string accessToken, DateTime now);
        Task<Response> RemoveExpiredRefreshTokens(DateTime Now);
        byte[] secret();

    }
    public class JwtAuth : IJwtAuth
    {
        private readonly JwtTokenConfig _jwtTokenConfig;
        private readonly ILogger _logger;
        private readonly DataAcsess DBA;
        private readonly byte[] _secret;

        public JwtAuth(JwtTokenConfig jwtTokenConfig, ILogger<IJwtAuth> logger)
        {
            DBA = new();
            _jwtTokenConfig = jwtTokenConfig;
            _logger = logger;
            _secret =  secret();
        }
        public byte[] secret() 
        {
          return  Encoding.ASCII.GetBytes(( DBA.GetData<string, dynamic>("select Secretkey from Secret where id = @Id", new { Id = "1" }).Result[0]));
        }

of course I have the SecretCommand and SecretHandel created.

Any ideas? And if what I'm doing is wrong, please advise me. for easier and secure way:)

If the signing key mentioned in the token (the kid claim) is not found in the JWKS endpoint, then you will get this error. The signing key used to sign the tokens must be present all the time, even when you redeploy your identity provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM