简体   繁体   中英

Check jwt token when project start in ASP.NET Core

I need to check jwt Token in Asp Core .

I create this extension method for inject in Service :

public static class AddJWTAuthntication
{
    public static void AddJWTAuthnticationInjection(this IServiceCollection services,SiteSetting siteSetting)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            var securityKey = Encoding.UTF8.GetBytes(siteSetting.JwtSetting.SecretKey);
            var ValidatePrameters = new TokenValidationParameters
            {
                //Tlorance for Expire Time and Befor Time of Token .
                ClockSkew = TimeSpan.Zero,
                RequireSignedTokens = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(securityKey),
                // I Need Check Expire Token or Not
                RequireExpirationTime = true,
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidAudience = siteSetting.JwtSetting.Audience,
                ValidateIssuer = true,
                ValidIssuer = siteSetting.JwtSetting.Issuer

            };
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = ValidatePrameters;
        });
    }
}

and use it in service extension in StartUp :

           services.AddJWTAuthnticationInjection(_siteSetting);

and this is my Configure :

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
        app.UseRouting();

        app.UseCors(builder => builder
                     .AllowAnyHeader()
                     .AllowAnyMethod()
                     .SetIsOriginAllowed((host) => true)
                     .AllowCredentials()
                    );
        app.UseAuthorization();
        app.UseAuthentication();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
}

Now when I run the project it go to the AddJWTAuthnticationInjection for check validation but when I send the request it not go to AddJWTAuthnticationInjection for check Token Validation .

I need to reverse that, when user send a request it check the Validation of Token .

What's the problem? How can I solve it?

This is not about token validation! You are setting up the ASP.NET Core's Authentication Middleware with your settings so this process needs to be executed once and it happens at the start-up of your application.

The token validation happens internally in the Authentication Middleware (where you have used app.UseAuthentication() in the Configure method of the StartUp.cs ). So you don't need to worry about the process of validation, you just take care of the settings you did in your AddJWTAuthnticationInjection method.

  • You have misplaced the Authentication Middleware and Authorization Middleware in your configure method. The Authentication Middleware needs to come before Authorization Middleware like this

    app.UseAuthentication(); app.UseAuthorization();
  • Don't forget to add the [Authorize] Attribute on your controller to enable the token validation

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