【问题标题】:Authorize attribute does not work授权属性不起作用
【发布时间】:2014-10-27 04:32:09
【问题描述】:

我已经下载了 Microsoft.AspNet.Identity.Samples Pre,位于: https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples

另外,我还改编了一个来自 GitHub 的示例。

在这两种情况下,每当我尝试访问“RolesAdmin”即 ~/rolesadmin/ 页面时,它都会将我踢回登录页面。

我已经确认用户已经登录并且属于Admin角色,那么为什么Authorize属性不允许我进入roleadmin页面呢?

namespace IdentitySample.Controllers
{
    [Authorize(Roles = "Admin")]
    public class RolesAdminController : Controller
...

这是我的确认代码(ViewBag.IsLoggedIn 和 ViewBag.IsAdmin 在登录后都返回 true:

  if (User.Identity.IsAuthenticated)
            {
                MyDbContext context = new MyDbContext();

                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

                var appUser = UserManager.FindByName("Admin");

                var userIsInRole = UserManager.IsInRole(appUser.Id, "Admin");
                ViewBag.IsLoggedIn = true;
                ViewBag.IsAdmin = userIsInRole;
            }
            else
            {
                ViewBag.IsLoggedIn = false;
                ViewBag.IsAdmin = false;
            }

如果那里有 ASP.NET Identity 2.1.0 的良好示例代码 - 请告诉我。

为什么我无法访问此控制器?

我看过这个页面: MVC 5 Asp.Net Identity Authorize Attribute error

还有这个页面: ASP.NET Identity - Confusion about [Authorize] And RoleManager

还有这个页面: Custom Forms Authentication + MVC3 + AuthorizeAttribute

似乎没有任何帮助。

注意:我正在使用带有最新工具更新 SQL Server 2012 express 的 VS2012。 此外,在其中一个代码示例中,您将看到我创建了一个名为 Admin 的用户和一个名为 Admin 的角色 - 我只是复制了我必须承认的代码。

web.config 的相关部分似乎没有任何区别:

<membership>
      <providers>
        <clear />
      </providers>
    </membership>

    <roleManager enabled="true">
      <providers>
        <clear />
      </providers>
    </roleManager>

   <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" >
      <remove name="RoleManager" />
    </modules>
  </system.webServer>



public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new AuthorizeAttribute()); // Added this in a vein attempt
        }
    }

创业班

public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

AccountController 上的登录代码:

 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

SignInAsync 代码:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            // Add more custom claims here if you want. Eg HomeTown can be a claim for the User
            //var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown);
            //identity.AddClaim(homeclaim);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }

我希望 Microsoft 示例能够开箱即用,这是我觉得最令人费解的......

【问题讨论】:

  • 您登录用户的代码在哪里?
  • 用代码更新答案
  • SignInAsync 的代码在哪里
  • 已添加 - 这与以某种方式与角色挂钩的声明有关?
  • 我刚刚添加了 identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));现在它可以工作了!

标签: c# asp.net-mvc sql-server-2012 asp.net-mvc-5 asp.net-identity-2


【解决方案1】:

答案:

1) 使用https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples -Pre

不要在您的网站上注册,然后期望获得对受 Authorize 属性保护的控制器的访问权限,并将 Roles 设置为 Admin。您的新用户不会被分配到管理员角色。 使用默认登录: admin@example.com,密码为 Admin@123456

2) 我发现从 asp.net 网站链接的这个 github 示例 (https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample) 要么被破坏(因为它没有手动添加单词“class”到类继承中就无法构建)或者只是出于日期。

3) 从示例中复制时请注意 web.config 和 sub-web.config 配置。

4) 您可能不希望集成我上面的一些代码,因为它不在示例中(有效的那个)。

现在我可以继续,不受阻碍地为我的家庭/酿造/园艺项目构建基于传感器 arduino yun 的信号记录、报告和可视化网站。

【讨论】:

  • UserManager.CreateIdentityAsync 这应该负责角色。事实并非如此,这意味着您的 UserManager 存在问题
  • 感谢@Shoe 的帮助 - 你可能是对的,我会再次检查样品,暂时把尾巴夹在两腿之间。
猜你喜欢
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 2015-09-09
  • 2015-01-06
  • 1970-01-01
  • 2016-05-14
相关资源
最近更新 更多