Token Authentication stopped working after migrati

2019-07-23 05:33发布

问题:

I followed this site to migrate my website from ASP.NET Core 1 to ASP.NET Core 2.

However after doing the ASP Identity changes my authentication stopped working.

My services look like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(_ => Configuration);

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddResponseCaching();

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    var secretKey = Configuration.GetSection("AppSettings")["SecretKey"];
    var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
    var tokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingKey,
        ValidateIssuer = true,
        ValidIssuer = "arnvanhoutte",
        ValidateAudience = true,
        ValidAudience = "User",
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
        });

    services.AddWebSocketManager();

    services.AddMvc();

    services.AddTransient<Seed>();
}

And I have app.UseAuthentication(); at the bottom of my Configure method.

However when I check var isAuthenticated = User.Identity.IsAuthenticated; this in a controller it always says false. It worked before though so I don't understand why this stopped working.

回答1:

I faced a similar issue during the migration

For me the login worked without any issue,but subsequent request failed with a redirect to the login page instead of throwing a 401(which caused a 404 as its a web api i didn't had any login page!).

Adding the defaultauthenticationscheme and DefaultChallengeScheme to the addauthentication did the trick for me.

Changing the addauthentication as follows to make the jwt authentication work!

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = tokenValidationParameters
            });