.NET Core 2.2 发出身份验证 cookie 但无法识别
.NET Core 2.2 sends out authentication cookie but doesn't recognise it
我正在使用 .NET Core 2.2 Web API 和 Angular 8 SPA。 Angular 位对于问题并不重要,但需要注意的重要一点是 我没有使用 MVC。
我还使用 EntityFramework 身份通过 Cookie 对用户进行身份验证。
为了测试,我使用 Insomnia。
我的登录端点有效,并生成一个 cookie,该 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身份,因此不需要此代码
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
身份验证服务已添加到您的服务 services.AddIdentity<ApplicationUser, IdentityRole>
我正在使用 .NET Core 2.2 Web API 和 Angular 8 SPA。 Angular 位对于问题并不重要,但需要注意的重要一点是 我没有使用 MVC。
我还使用 EntityFramework 身份通过 Cookie 对用户进行身份验证。
为了测试,我使用 Insomnia。
我的登录端点有效,并生成一个 cookie,该 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身份,因此不需要此代码
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
身份验证服务已添加到您的服务 services.AddIdentity<ApplicationUser, IdentityRole>