我迷失在ASP.Net Core 2 MVC应用程序中的身份验证。 我正在使用Core 2版本,似乎版本1和版本2之间有很多变化。我已经阅读了一些实际上不起作用的教程。
首先,这是我在ConfigureServices()
方法中放入 Startup.cs 的内容:
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]
以下是我在帖子操作登录方法中所做的:
[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
知道什么是错的?
答案 0 :(得分:4)
在Configure()
方法中将app.UseIdentity()
更改为:
app.UseAuthentication();
另请注意:如果您使用的是不带身份的Cookie(因为它出现在您的Index
操作中):
调用中的
AddAuthentication
和AddCookie
方法ConfigureServices
方法:// If you don't want the cookie to be automatically authenticated and assigned to HttpContext.User, // remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/LogIn"; options.LogoutPath = "/Account/LogOff"; });
补充阅读:Migrating Authentication and Identity to ASP.NET Core 2.0
答案 1 :(得分:0)
我通过执行自己的Logout()操作的方式修复了该问题,该操作删除了身份验证Cookie,然后重定向到起始页。为了可靠地做到这一点,我给了认证。使用ConfigureServices()
中的Startup.cs
方法对我自己的名字进行cookie。
Startup.cs:
private void ConfigureServices(IServiceCollection services)
{
..
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
options.Cookie.Name = "MyOwnCookieName";
});
...
HomeController.cs:
[Authorize]
[HttpGet]
public IActionResult Logout()
{
Response.Cookies.Delete("MyOwnCookieName");
return RedirectToAction("Index");
}
也许这为我节省了一些时间,因为我花了很多时间到达那里。