【发布时间】:2018-05-13 16:08:00
【问题描述】:
我迷失了 ASP.Net Core 2 MVC 应用程序中的身份验证。 我正在使用 Core 2 版本,版本 1 和 2 之间似乎有很多变化。我已经阅读了一些不太有效的教程。
首先,这是我在 Startup.cs 中 ConfigureServices() 方法的内容:
services.AddIdentity<MyUserClass, IdentityRole>()
.AddEntityFrameworkStores<MyDatabaseEFContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(150);
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});
这是我在Configure() 方法中输入的内容:
app.UseIdentity();
我在每个控制器的每个动作方法上都放了这个注解:
[Authorize]
这是我在我的 post action 登录方法中所做的:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var claims = new List<Claim> {new Claim(ClaimTypes.Name, model.Login)};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Index", "PrivateController");
}
当我尝试登录时出现此异常:
InvalidOperationException:没有配置身份验证处理程序来处理方案:Cookies
知道什么是错的吗?
【问题讨论】:
-
可能是您缺少
services.ConfigureApplicationCookie,如文档docs.microsoft.com/en-us/aspnet/core/security/authentication/…中所述 -
您使用的是 ASP.NET Identity 还是仅使用 cookie 身份验证?目前,您的代码同时使用两者。
标签: c# asp.net-core asp.net-core-2.0 asp.net-core-identity