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