gpt4 book ai didi

c# - ASP.Net Core 2 身份验证

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:05 24 4
gpt4 key购买 nike

我迷失了 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();

我把这个注解放在每个 Controller 的每个 Action 方法上:

[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: No authentication handler is configured to handle the scheme: Cookies

知道哪里出了问题吗?

最佳答案

在您的 Configure() 方法中,将 app.UseIdentity() 更改为:

app.UseAuthentication();

另请注意:如果您使用的 cookie 没有标识(如您的 Index 操作中所示):

Invoke the AddAuthentication and AddCookie methods in the ConfigureServices method:

// 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

关于c# - ASP.Net Core 2 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47561426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com