成功登录的用户不断被重定向到访问拒绝路径 ASP.NET 使用MVC CookieAuthentication



我将 [Authorize] 属性添加到主控制器。

当用户登录时,此处是运行的代码:

[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);
}

我看到创建了 2 个饼干,这是正确的。

当我尝试从主控制器访问页面时,我被推送到我在 Startup 中设置的禁止页面.cs:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyAppCookieMiddleware",
LoginPath = new PathString("/Auth/Login/"),
AccessDeniedPath = new PathString("/Auth/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});

尝试将行从

principal.AddIdentity(new ClaimsIdentity(claims));

principal.AddIdentity(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));

只是为了补充索汉姆的答案,你可能想读这篇文章。

使用构造函数时

ClaimsIdentity(IEnumerable<Claim> claims)

属性AuthenticationType的值为null。属性IsAuthenticated的返回值为"true,如果 AuthenticationType 属性不为 null 或空字符串"。

使用构造函数

ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType)

如果值不为null 也不为空,authenticationType将导致isAuthenticated属性返回True

相关内容

  • 没有找到相关文章

最新更新