简体   繁体   中英

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!

your code contains some typos and it is not clear!

for example, the below code is only for finding a user not for creating;

// create user and save tahat to the db
var user = manager.Find(userName, password);

also authenticationManger should start with capital letter, and where is userIdentity coming from?

AuthenticationManger.SignIn(new AuthenticationProperties
{
   IsPersistent = false
}, userIdentity);

try it with SignInManager like below:

public string ValidateUser(string userName, string password)
{
    var result = SignInManager.PasswordSignIn(userName, password, false, false);
    if(result==SignInStatus.Success)
        return userName;

    ModelState.AddModelError("", "Invalid login attempt.");
        //return View(model);
        return View();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM