2

I have downloaded the Microsoft.AspNet.Identity.Samples Pre found at: https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples

Also, I have also adapted a sample from GitHub.

In both cases whenever I try to access the "RolesAdmin" i.e. ~/rolesadmin/ page, it kicks me back to the login page.

I have confirmed the user is logged in and belongs to the Admin role, so why does the Authorize attribute not permit my entry into the roleadmin page?

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

Here's my code for confirming (ViewBag.IsLoggedIn and ViewBag.IsAdmin both come back as true once logged in:

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

If there is a good sample code for ASP.NET Identity 2.1.0 out there - please let me know.

Why can I not access this controller?

I have looked at this page: MVC 5 Asp.Net Identity Authorize Attribute error

And this page: ASP.NET Identity - Confusion about [Authorize] And RoleManager

And this page: Custom Forms Authentication + MVC3 + AuthorizeAttribute

None of it seems to help.

Notes: I am using VS2012 with the latest tools update, SQL Server 2012 express. Also, in one of the code samples you will see I have created a user called Admin and role called Admin - I just copied the code I have to admit.

Relevant bit of web.config seems to make no difference:

<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
        }
    }

Start-up class

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

Login code on 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 code:

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

I would expect the Microsoft sample to work out of the box which is what I find most baffling...

Community
  • 1
  • 1
DanAbdn
  • 7,151
  • 7
  • 27
  • 38

1 Answers1

0

Answer:

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

Don't register in your website and then expect to gain access to your controller protected by Authorize attribute with Roles set to Admin. Your new user will not be assigned to the Admin role. Use the default login: admin@example.com with password Admin@123456

2) I found this github sample (https://github.com/rustd/AspnetIdentitySample/tree/master/AspnetIdentitySample) linked from the asp.net website to be quite either broken (because it did not build without manually adding the word "class" to a class inheritance) or simply out of date.

3) Be wary of web.config and sub-web.config configuration when copying from the sample.

4) You may wish not to integrate some of my code above as it is not in the sample (the one that works).

Now I may continue, unhindered to build my sensor arduino yun based signalr logging, reporting and visualisation website for my home/brewing/gardening projects.

DanAbdn
  • 7,151
  • 7
  • 27
  • 38
  • `UserManager.CreateIdentityAsync` this should take care of roles. The fact that it isn't means there's an issue with your `UserManager` – jamesSampica Sep 02 '14 at 20:32
  • Thanks for your help @Shoe - you are probably right and I will examine the sample again and tuck my tail between my legs for the moment. – DanAbdn Sep 02 '14 at 20:39