User987 User987 - 1 year ago 91
ASP.NET (C#) Question

Unable to access Controller action after sign in and adding Authorize attribute to the Action

I've set up a simple login page to login my user when he clicks the login button. The user gets assigned roles upon the login. To test if it works out I've done the following code for login:

public ActionResult Login(LoginViewModel model)
if (ModelState.IsValid)
string userName = model.Username;
string[] userRoles = new string[5];
userRoles[0] = "Administrator";

ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

// userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));
identity.AddClaim(new Claim(ClaimTypes.Role, userRoles[0]));
identity.AddClaim(new Claim(ClaimTypes.Name, userName));


return RedirectToAction("Success");
return View("Login",model);

And I've added a Authorize attribute to my MVC action, just to see if the user will really be able to access it after the login... Here's how I've done it:

public ActionResult Register()
var model = new UserRegistrationViewModel();
var countries = Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();
model.Countries = new SelectList(countries, "CountryId", "CountryName");
return View(model);

But for some reason when I try to access like following:

It shows me:

HTTP Error 401.0 - Unauthorized
You do not have permission to view this directory or page.

What could it be ?


Here is the snapshot of claims and identities after the user logs in:

enter image description here

And 2nd one:

enter image description here

Win Win
Answer Source

Could you ensure that you have Cookie middleware? For example,


[assembly: OwinStartup(typeof(YourApplicationName.Startup))]
namespace YourApplicationName
    public class Startup
        public void Configuration(IAppBuilder app)
            app.UseCookieAuthentication(new CookieAuthenticationOptions
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")

Using Cookie Middleware without ASP.NET Core Identity

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download