我想在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);
}
之后。
在屏幕截图中找到正确的位置。
答案 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);