c# - Cookie 身份验证在 ASP.NET Core 应用程序中不起作用
问题描述
我正在尝试在 .NET Core 3.1 中开发一个项目。我正在尝试在我的项目中实现基于 cookie 的身份验证。我的登录功能是:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(UserLoginModel userModel)
{
if (!ModelState.IsValid)
{
return View(userModel);
}
if (userModel.Email == "admin@test.com" && userModel.Password == "123")
{
var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "User Id"));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Name"));
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);
return RedirectToAction(nameof(HomeController.Index), "Home");
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
return View();
}
}
为了实现基于 cookie 的身份验证,我将以下代码放在 Startup 类的 ConfigureService 方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "_auth";
options.Cookie.HttpOnly = true;
options.LoginPath = new PathString("/account/login");
options.LogoutPath = new PathString("/account/logout");
options.AccessDeniedPath = new PathString("/account/login");
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.SlidingExpiration = false;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
}
Startup 类的配置方法是:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
但问题是每次我尝试登录时,登录操作方法的以下代码都会出现以下异常。
等待 HttpContext.SignInAsync(IdentityConstants.ApplicationScheme,主体)
发生的异常如下所示:
InvalidOperationException:没有为方案“Identity.Application”注册登录身份验证处理程序。注册的登录方案是: Cookies。您是否忘记调用 AddAuthentication().AddCookies("Identity.Application",...)?Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties) _01_AuthenticationDemo.Controllers.AccountController.Login(UserLoginModel userModel) in AccountController.cs + await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);
谁能给我解决问题的建议。
解决方案
没有为方案“Identity.Application”注册登录身份验证处理程序。注册的登录方案是: Cookies。
请使用 进行分隔CookieAuthenticationDefaults.AuthenticationScheme
,如下所示。
if (userModel.Email == "admin@test.com" && userModel.Password == "123")
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "User Id"));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Name"));
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction(nameof(HomeController.Index), "Home");
}
测试结果
推荐阅读
- react-native - 用 Jest 在 React Native 中测试 TextInput 的值变化
- xamarin.forms - Xamarin Forms - 如何使用 PushModalAsync 从右到左为模式设置动画?
- elasticsearch - 查询 ~10M 文档索引和更多问题时 fielddata=true 会有什么影响
- javascript - React Native 无法返回数组
- ruby - 我需要一个 cron 表达式
- laravel-5.2 - 使用带变量的控制器路由时出现问题
- apache-drill - Apache Drill 不使用整个直接内存
- python - 覆盖导入的类变量 - django/python
- sql - SQL 括号在哪里需要条件?
- elixir - 使用 Timex 间隔