【发布时间】:2019-09-16 08:06:36
【问题描述】:
当我使用 Authorize roles 属性装饰方法时,它每次都返回 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);
}
【问题讨论】:
-
在对用户进行身份验证后,您如何构建您的 Claimsprincipal?
-
@Jinish 请参阅更新 1
-
您也可以手动创建 FormsAuthenticationTicket。构造函数采用 userdata 参数,您可以在其中添加身份验证时的角色。将其添加到 httpresponse cookie 集合中的帖子。然后你可以使用你的 User.IsInRole
标签: c# asp.net-mvc authorization asp.net-identity identity