首页 > 解决方案 > .NET Core 2.2 发出身份验证 cookie 但无法识别

问题描述

我正在使用带有 Angular 8 SPA 的 .NET Core 2.2 Web API。Angular 位对这个问题并不重要,但需要注意的重要一点是我没有使用 MVC

我还使用 EntityFramework Identity 通过 Cookie 对用户进行身份验证。

对于我的测试,我正在使用Insomnia

我的登录端点工作,并产生一个 cookie,由 Insomnia 存储并在未来的请求中重新发送。

我的问题从这里开始。我目前无法让应用程序识别 cookie,并且我的 API 响应401 Unauthorized任何标有该属性的端点,[Authorize]尽管有一个有效期为 7 天的有效 cookie。

这是我的Startup.cs文件:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddSwaggerGen(x =>
        {
            // stuff
        });

        services.AddDbContext<SensoLicensingContext>(options => {
            // stuff
        });

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

        services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.Headers["Location"] = context.RedirectUri;
                context.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
        });

        services.AddTransient<IEmailSender, EmailSender>();
        services.Configure<AuthMessageSenderOptions>(options =>
            Configuration.GetSection("SendGridEmailSettings").Bind(options));

        services
            .AddMvcCore()
            .AddApiExplorer()
            .AddAuthorization()
            .AddFormatterMappings()
            .AddJsonFormatters()
            .AddCors()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();

            // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });
    }

    public void Configure(IApplicationBuilder app, 
                IHostingEnvironment env, 
                UserManager<ApplicationUser> userManager,
                RoleManager<IdentityRole> roleManager,
                LicensingContext dbContext)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint(Constants.SwaggerEndPointUrl, Constants.SwaggerEndPointName);
            });
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
            app.UseHttpsRedirection();
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseAuthentication();

        dbContext.Database.EnsureCreated();
        IdentityDataInitializer.SeedData(userManager, roleManager);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }

我觉得问题出在这部分,要么是我的订购,要么完全是在错误的地方,但我对 .NET Core 比较陌生,所以我不确定:

services
    .AddMvcCore()
    .AddApiExplorer()
    .AddAuthorization()
    .AddFormatterMappings()
    .AddJsonFormatters()
    .AddCors()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

任何帮助将不胜感激。

标签: asp.net-coreasp.net-web-apiasp.net-identity

解决方案


由于您使用的是 ASP.NET Identity,因此不需要此代码

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

身份验证服务已添加到您的服务中services.AddIdentity<ApplicationUser, IdentityRole>


推荐阅读