Asp.net Core 2.0 基本 JWT 缺少 ApplicationCookie

Posted

技术标签:

【中文标题】Asp.net Core 2.0 基本 JWT 缺少 ApplicationCookie【英文标题】:Asp.net Core 2.0 basic JWT missing ApplicationCookie 【发布时间】:2018-01-24 09:33:53 【问题描述】:

我目前正在将我的 Web API 项目升级到 .NET Core 2.0 并且似乎 AddIdentity.Cookies 不再可用。

谁能指出我正确的方向?

 public void ConfigureServices(IServiceCollection services)
    
        services.AddSingleton(Configuration);

        services.AddMvc();

        // Add framework services.
        services.AddDbContext<ApplicationContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddDbContext<AuthContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AuthConntection")));

        services.AddIdentity<ApplicationUser, MyRole>(cfg =>
        
            cfg.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
            
                OnRedirectToLogin = ctx =>
                
                    if (ctx.Request.Path.StartsWithSegments("/api"))
                        ctx.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                    return Task.FromResult(0);
                
            ;
        )
            .AddUserStore<ApplicationUserStore>()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<AuthContext, Guid>();

【问题讨论】:

【参考方案1】:

根据 GitHub 上的代码,我觉得你应该使用ConfigureApplicationCookie

services.AddIdentity<ApplicationUser, MyRole>();
services.ConfigureApplicationCookie(options =>

    options.Events = new CookieAuthenticationEvents
    
    ;
);

GitHub上的扩展方法:https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/IdentityServiceCollectionExtensions.cs#L39

【讨论】:

以上是关于Asp.net Core 2.0 基本 JWT 缺少 ApplicationCookie的主要内容,如果未能解决你的问题,请参考以下文章