简体   繁体   English

登录后仍无法使用[Authorize(Roles =“ Admin”)]访问ASP.NET MVC控制器方法

[英]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. 我已经在控制器中创建了登录方法,并且正在通过JavaScript AJAX调用进行登录。 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 但是,当我尝试访问具有Authorize(Roles = "Admin")的控制器方法时,我将无法执行此操作,并且每次将其发送到UnAuthorize页面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 为什么我无法访问Controller方法我的user with same admin role每个user with same admin roleuser with same admin role ,因此登录过程有什么问题,并且登录页面不是强类型的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 这是我对登录方法的ajax调用

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 这行代码返回true

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

and This line of code returns false 并且此行代码返回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也应该以大写字母开头, userIdentity来自哪里?

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

try it with SignInManager like below: 尝试使用SignInManager如下所示:

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 问题是我在将OWIN扩展到基于role和基于group的授权之前创建的用户无效,因此,每次创建新用户时, SecurtyStamp需要像这样更新其SecurtyStamp来添加此新行

await UserManager.UpdateSecurityStampAsync(user.Id);

Hope this helps any one 希望这对任何人有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.Net MVC 4中授权管理控制器 - Authorize Admin Controller in ASP.Net MVC 4 来自区域中控制器的ASP.NET MVC [Authorize]在根文件夹中找不到Account / Login ActionResult - ASP.NET MVC [Authorize] from controller in area can't find Account/Login ActionResult in root folder `[Authorize(Roles =“admin”)]`无限循环ASP.NET MVC和Azure Active Directory B2C - `[Authorize(Roles = “admin”)]` Infinite loop ASP.NET MVC and Azure Active Directory B2C 在ASP.NET中,“ [[Authorize(Roles = ADMIN)]]”中的括号是什么意思? - What do the brackets in “[Authorize(Roles = ADMIN)]” mean in ASP.NET? ASP.NET Core 标识 [Authorize(Roles =&quot;ADMIN&quot;)] 不起作用 - ASP.NET Core Identity [Authorize(Roles ="ADMIN")] not work 授权 asp.net 中的角色 - authorize roles in asp.net 无法访问控制器(ASP.NET MVC) - Can not access a controller (ASP.NET MVC) ASP.NET MVC授权具有许多角色的用户 - ASP.NET MVC Authorize user with many roles Asp.Net MVC C#[Authorize(Roles“”)]不起作用 - Asp.Net MVC C# [Authorize(Roles“”)] not working 如何在没有数据库的情况下在 ASP.NET Core 中创建一个简单的登录并授权控制器访问 - How to create a simple login in ASP.NET core without database and authorize controller access
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM