c# - 从 ASP.NET Core 1 迁移到 ASP.NET Core 2 后, token 身份验证停止工作

标签 c# asp.net .net-core

我关注了这个site将我的网站从 ASP.NET Core 1 迁移到 ASP.NET Core 2。

但是在执行 ASP 身份更改后,我的身份验证停止工作。

我的服务是这样的:

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>();
}

我的 Configure 方法底部有 app.UseAuthentication();

但是,当我在 Controller 中检查 var isAuthenticated = User.Identity.IsAuthenticated; 时,它总是说 false。虽然它之前有效,但我不明白为什么它停止工作。

最佳答案

我在迁移过程中遇到了类似的问题

对我来说,登录没有任何问题,但随后的请求失败了,重定向到登录页面而不是抛出 401(这导致 404 作为其 一个 web api 我没有任何登录页面!)。

将 defaultauthenticationscheme 和 DefaultChallengeScheme 添加到 addauthentication 对我有用。

如下更改 addauthentication 以使 jwt 身份验证工作!

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

关于c# - 从 ASP.NET Core 1 迁移到 ASP.NET Core 2 后, token 身份验证停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45824690/

相关文章:

c# - Transactionscope 抛出异常此平台在打开连接对象时不支持分布式事务

c# - .Net 5发布单个文件-生成exe和dll

c# - 是否有一些库可以在其属性中创建带有虚拟数据的对象实例?

c# - 从不同线程调用方法 AutoResetEvent 是否安全?

asp.net - 网页背景图片未显示

c# - System.ObjectDisposedException : The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

c# - 显示标签消息而不点击

c# - 为什么尝试在WPF/C#中注册所有事件时出现构建错误?

c# - 如何更新此类/方法以改进代码指标

c# - 使用 Entity Framework Core 2.0 在不丢失数据的情况下更改或重命名列名