Dummy Dummy - 2 months ago 12
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 =
System.Configuration.ConfigurationManager
.ConnectionStrings["Test"].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);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return userName;
}


This is my ajax call to the login method

function ValidateUser() {
debugger;
var userName = document.getElementById('username').value;
var password = document.getElementById('password').value;
var url = "/Public/ValidateUser/";
$("#btnLogin").val('Plesae wait..');
$.ajax({
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 {
$(".alert").show();//.delay(5000).fadeOut('slow');
setTimeout(function () { $(".alert").fadeOut(); }, 2000);
//location.href = "/Public/login";
}
$("#username").attr({ 'value': '' });
$("#password").attr({ 'value': '' });
},
error: function (reponse) {
alert("error : " + reponse);
}
});
$("#btnLogin").val('Login');
event.preventDefault();
}


UPDATE

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

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