簡體   English   中英

授權屬性不起作用

[英]Authorize attribute does not work

我已經下載了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身份授權屬性錯誤

本頁: ASP.NET身份-關於[授權]和RoleManager的混淆

本頁: 自定義表單身份驗證+ MVC3 + AuthorizeAttribute

似乎沒有幫助。

注意:我正在將VS2012與最新的工具更新(SQL Server 2012 Express)一起使用。 另外,在其中一個代碼示例中,您將看到我創建了一個名為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);
        }

登錄異步代碼:

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示例可以立即使用,這是我最困惑的地方。

回答:

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

不要在您的網站上注冊,然后希望獲得對您的控制器的訪問,該控制器受Roleize設置為Admin的Authorize屬性保護。 您的新用戶將不會被分配為管理員角色。 使用默認登錄名:admin@example.com,密碼為Admin @ 123456

2)我發現從asp.net網站鏈接的這個github示例( https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample )相當不完整(因為如果沒有手動添加“類”繼承到類繼承)或完全過時。

3)從示例復制時,請警惕web.config和sub-web.config配置。

4)您可能不希望在上面集成我的某些代碼,因為它不在示例中(有效的代碼)。

現在,我可以不受阻礙地繼續為我的家庭/飼養/園藝項目構建基於arduino yun傳感器的信號記錄,報告和可視化網站。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM