Dummy Dummy - 1 year ago 64
ASP.NET (C#) Question

can not get access to the ASP.NET MVC controller method with [Authorize(Roles = "Admin")] even after login

Implemented Identity, and I've stared it from scratch. I've created a login method in controller and I'm getting login through an JavaScript AJAX call.
But when I try to access a controller method which has a

Authorize(Roles = "Admin")
I can not do that and every time it send me to the UnAuthorize page 401

Why I'm not able to get access to the Controller method I've
user with same admin role
every thing as accordingly, whats wrong with my login process, and my login page is not a strongly type View

Here is my controller method

[Authorize(Roles = "Admin")]
public ActionResult Create()
return View();

My Login method

public string ValidateUser(string userName, string password)
var userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString =

var manager = new UserManager<IdentityUser>(userStore);

// create user and save tahat to the db
var user = manager.Find(userName, password);
if (ModelState.IsValid)
// var user = await UserManager.FindAsync(userName, password);
if (user != null)
//sign in user
authenticationManger.SignIn(new AuthenticationProperties
IsPersistent = false
}, userIdentity);
ModelState.AddModelError("", "Invalid username or password.");
return userName;

This is my ajax call to the login method

function ValidateUser() {
var userName = document.getElementById('username').value;
var password = document.getElementById('password').value;
var url = "/Public/ValidateUser/";
$("#btnLogin").val('Plesae wait..');
url: url,
data: { UserName: userName, Password: password },
cache: false,
type: "POST",
success: function (data) {
if (data === userName && userName !== "") {
//alert("Successfull login.");
location.href = "/Home/Index";
} else {
setTimeout(function () { $(".alert").fadeOut(); }, 2000);
//location.href = "/Public/login";
$("#username").attr({ 'value': '' });
$("#password").attr({ 'value': '' });
error: function (reponse) {
alert("error : " + reponse);


This line of code returns true

var useris = manager.IsInRole(user.Id, "Admin");

and This line of code returns false

var user= User.Identity.GetUserId();

What is wrong Please!

Answer Source

The problem was the user I created before extending my OWIN to role based and group based Authorization became null and void so I'd to add this new line every time I create a new user its SecurtyStamp needed to be updated like this

await UserManager.UpdateSecurityStampAsync(user.Id);

Hope this helps any one