首页 > 解决方案 > 授权属性总是返回错误的 ASP.net MVC 身份

问题描述

当我使用 Authorize 角色属性装饰方法时,它每次都返回 false。我正在尝试仅限制“管理员”角色的用户访问管理页面。

  1. 我已经验证用户即时登录实际上是在“管理员”角色中。

  2. 我尝试使用自定义授权属性。结果相同。如果需要,我可以添加代码。

  3. 我发现授权属性适用于用户,但不适用于角色。

  4. 我相信这个问题在某种程度上与以下事实在我的应用程序中不起作用有关:

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


    }

也许这可以帮助调试:

用户 分配给角色的用户 用户 ID 分配给角色

我愿意接受有关我可以从我的项目中发布的任何其他内容的建议,以便更轻松地进行调试。我已经搜索堆栈 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);
    }

标签: c#asp.net-mvcauthorizationasp.net-identityidentity

解决方案


FormsAuthentication.SetAuthCookie(identity.Name, isPersistent);

不幸的是,不存储任何具有身份的角色。因此,当从 cookie 重新创建身份时,您没有任何角色。验证尝试

this.User.IsInRole("Admin")

你会得到false,即使userManager告诉你不是这样。

有多种解决方法。

例如,您可以切换到任何其他身份持久化器,例如SessionAuthenticationModule可以将您的用户名和角色存储在 cookie 中的持久化器。您可以按照我的教程进行操作。

另一种方法是使用显式角色管理器并使用其功能自动将您的角色存储在另一个 cookie 中,与表单身份验证 cookie 分开。这包括配置角色提供者和编写您自己的角色提供者,该角色提供者将成为用户管理器的适配器。

最后,您可能会忘记表单身份验证并使用 Identity 的本机方式来发布 cookie,这将涉及调用SignInAsync身份验证管理器。


推荐阅读