ASP.NET Core 2没有配置身份验证处理程序来处理该方案

时间:2017-09-01 05:07:49

标签: c# asp.net asp.net-core authorization

我想在ASP.NET Core 2应用程序中提供授权。 在使用帐户/登录中的数据发送模型后,在调用1e-10之后,我收到一条错误消息。 我无法理解哪里缺乏描述。

Startup.cs

await Authenticate(user)

的AccountController

//ConfigureServices
services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie("TmiginScheme", options =>
{
    options.LoginPath = "/Account/Login";
    options.LogoutPath = "/Account/Logout";
    options.ExpireTimeSpan = TimeSpan.FromHours(1);
    options.SlidingExpiration = true;
});

//Configure
app.UseAuthentication();

固定

不起作用,因为我将代码放在[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginModel model) { if (ModelState.IsValid) { User user = null; Cryptex cryptex = new Cryptex(); string password = cryptex.EncryptText(model.Password, "TMigin"); // Ищем user user = fStorage.Users.GetUserByLogin(model.Login); if (user != null) { if (string.Compare(user.Password, password) != 0) { user = null; } } if (user != null) { await Authenticate(user); return RedirectToAction("Index", "CMS"); } else { // Логируем ошибку входа ModelState.AddModelError("", "Ошибка входа"); } } return View(model); } private async Task Authenticate(User user) { var claims = new List<Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, user.Name), new Claim("CMS", "True") }; var identity = new ClaimsIdentity(claims); var principal = new ClaimsPrincipal(identity); await HttpContext.Authentication.SignInAsync("TmiginScheme", principal); } 之后。 在屏幕截图中找到正确的位置。

correctly

2 个答案:

答案 0 :(得分:6)

我遇到了同样的问题,但是作者的解决方案对我来说并不起作用。 我正在从.NET Core 1.1迁移到.NET Core 2.0。

就我而言,我正在使用:

await HttpContext.Authentication.SignInAsync(...);
await HttpContext.Authentication.SignOutAsync(...);

我应该使用:

await HttpContext.SignInAsync(...);
await HttpContext.SignOutAsync(...);

答案 1 :(得分:2)

我想问题是你在使用Cookies时将默认方案配置为options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;,而在使用TmiginScheme时使用的是AddCookie("TmiginScheme"的不同方案

AccountController中创建新ClaimsIdentity而未指定身份验证类型,最后您尝试使用不同于options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;中指定的方案名称登录。

要解决您的问题,请将AddCookie("TmiginScheme"更改为.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme

var identity = new ClaimsIdentity(claims);更改为var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

最后将await HttpContext.Authentication.SignInAsync("TmiginScheme", principal);更改为await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);