C# 成功登录的用户继续使用ASP.NET MVC CookieAuthentication重定向到AccessDeniedPath
我向主控制器添加了[Authorize]属性 当用户登录时,以下是运行的代码:C# 成功登录的用户继续使用ASP.NET MVC CookieAuthentication重定向到AccessDeniedPath,c#,asp.net,asp.net-core,asp.net-core-mvc,asp.net-identity,C#,Asp.net,Asp.net Core,Asp.net Core Mvc,Asp.net Identity,我向主控制器添加了[Authorize]属性 当用户登录时,以下是运行的代码: [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsV
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
User user = AuthManager.AuthenticateUser(model.Email, model.Password);
if (user != null && user.Authenticated)
{
ClaimsPrincipal principal = new ClaimsPrincipal();
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
new Claim(ClaimTypes.Email, user.Email)
};
// Add role claims
foreach (RoleResource role in user.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, role.Name));
}
principal.AddIdentity(new ClaimsIdentity(claims));
AuthenticationProperties authProperties = new AuthenticationProperties()
{
IsPersistent = model.RememberMe,
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)
};
await HttpContext.Authentication.SignInAsync("MyAppCookieMiddleware", principal, authProperties);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
试着将线路从
principal.AddIdentity(new ClaimsIdentity(claims));
到
试着将线路从
principal.AddIdentity(new ClaimsIdentity(claims));
到
只是为了补充,你可能需要阅读
当您使用构造函数时
ClaimsIdentity(IEnumerable<Claim> claims)
如果authenticationType
的值既不为null也不为空,则isAuthenticated
属性将返回True
,您可能需要读取
当您使用构造函数时
ClaimsIdentity(IEnumerable<Claim> claims)
如果
authenticationType
的值不为null或为空,将导致isAuthenticated
属性返回True
我不能放置超过2个链接。您可以看到可用的构造函数以及它们初始化的属性。我不能放置超过2个链接。您可以查看可用的构造函数及其初始化的属性。调试时,您的代码是否达到SignInAsync
方法调用?@Win Yes,它创建cookie。调试时,您的代码是否达到SignInAsync
方法调用?@Win Yes,它创建cookie。非常感谢!事实上,我最终移除了这个,但我从未意识到这是开始把事情搞砸的原因。我不记得默认值是什么,但它是一些随机字符串,所以我刚刚摆脱了它。非常感谢!事实上,我最终移除了这个,但我从未意识到这是开始把事情搞砸的原因。我记不起默认值是什么,但它是一些随机字符串,所以我只是去掉了它。
ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType)