c# - 授权属性总是返回错误的 ASP.net MVC 身份
问题描述
当我使用 Authorize 角色属性装饰方法时,它每次都返回 false。我正在尝试仅限制“管理员”角色的用户访问管理页面。
我已经验证用户即时登录实际上是在“管理员”角色中。
我尝试使用自定义授权属性。结果相同。如果需要,我可以添加代码。
我发现授权属性适用于用户,但不适用于角色。
我相信这个问题在某种程度上与以下事实在我的应用程序中不起作用有关:
User.IsInRole("Admin").
但是,此语句确实有效:
userManager.IsInRole(user.Id, "Admin")
这是我的代码:
public class AdminController : Controller
{
//[AuthLog(Roles = "Admin")] //Custom authorization attribute
[Authorize(Roles = "Admin")]
public ActionResult Users()
{
return View();
}
}
也许这可以帮助调试:
- Microsoft.AspNet.Identity.Core:V.2.1.0
- Microsoft.AspNet.Identity.EntityFramework:V.2.1.0
我愿意接受有关我可以从我的项目中发布的任何其他内容的建议,以便更轻松地进行调试。我已经搜索堆栈 2 周了。
更新 1:用户如何登录
// POST: /account/login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(AccountLoginModel viewModel)
{
// Ensure we have a valid viewModel to work with
if (!ModelState.IsValid)
return View(viewModel);
// Verify if a user exists with the provided identity information
var user = await _manager.FindByEmailAsync(viewModel.Email);
// If a user was found
if (user != null)
{
// Then create an identity for it and sign it in
await SignInAsync(user, viewModel.RememberMe);
// If the user came from a specific page, redirect back to it
return RedirectToLocal(viewModel.ReturnUrl);
}
// No existing user was found that matched the given criteria
ModelState.AddModelError("", "Invalid username or password.");
// If we got this far, something failed, redisplay form
return View(viewModel);
}
private async Task SignInAsync(IdentityUser user, bool isPersistent)
{
// Clear any lingering authencation data
FormsAuthentication.SignOut();
// Create a claims based identity for the current user
var identity = await _manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
// Write the authentication cookie
FormsAuthentication.SetAuthCookie(identity.Name, isPersistent);
}
解决方案
这
FormsAuthentication.SetAuthCookie(identity.Name, isPersistent);
不幸的是,不存储任何具有身份的角色。因此,当从 cookie 重新创建身份时,您没有任何角色。验证尝试
this.User.IsInRole("Admin")
你会得到false
,即使userManager
告诉你不是这样。
有多种解决方法。
例如,您可以切换到任何其他身份持久化器,例如SessionAuthenticationModule
可以将您的用户名和角色存储在 cookie 中的持久化器。您可以按照我的教程进行操作。
另一种方法是使用显式角色管理器并使用其功能自动将您的角色存储在另一个 cookie 中,与表单身份验证 cookie 分开。这包括配置角色提供者和编写您自己的角色提供者,该角色提供者将成为用户管理器的适配器。
最后,您可能会忘记表单身份验证并使用 Identity 的本机方式来发布 cookie,这将涉及调用SignInAsync
身份验证管理器。
推荐阅读
- python - 在 Bokeh Google Map Offline 上重新绘制
- php - 多条 SQL 输出
- python-3.x - Create multiple objects from list of strings python
- c++ - 我应该为地图使用哪种数据结构?(C++)
- java - Android开发:ID在变量中时如何访问字符串?
- ios - Object Swift 中的 Array 中的对象
- java - 自定义类型?如果我们可以这么说
- java - 在不断退出的 docker 容器中安装自定义包
- python-3.x - 在 Jupyter 中向 nbconvert 原始单元格添加语法高亮
- browser-cache - 注销后,当单击返回按钮时,由于 october cms 中的缓存问题,会出现安全的上次访问页面。如何防止这种情况?