Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么authorize属性无法在有效用户登录时授权操作?_C#_Asp.net_Asp.net Mvc_C# 4.0 - Fatal编程技术网

C# 为什么authorize属性无法在有效用户登录时授权操作?

C# 为什么authorize属性无法在有效用户登录时授权操作?,c#,asp.net,asp.net-mvc,c#-4.0,C#,Asp.net,Asp.net Mvc,C# 4.0,我正在对操作使用authorize属性 [Authorize(Users= "admin" )] [HttpGet] public JsonResult GetServices() { return Json(ServicesRepository.SelectServices(), JsonRequestBehavior.AllowGet); } 成功登录时,我正在设置: Session["Users"] = usersModels; Sessio

我正在对操作使用authorize属性

[Authorize(Users= "admin" )]
[HttpGet]
public JsonResult GetServices()
{
    return Json(ServicesRepository.SelectServices(), JsonRequestBehavior.AllowGet);
}
成功登录时,我正在设置:

Session["Users"] = usersModels;                   
Session["UHTUserName"] = usersModels.UserName;
FormsAuthentication.SetAuthCookie(usersModels.UserName, LoginVM.RememberMe);

AuthorizeAttribute aattr = new AuthorizeAttribute();

aattr.Users = usersModels.UserName;

但是,它仍然无法授权。

您是否在web.config中设置了表单身份验证的设置

<system.web>
    <authentication mode="Forms"></authentication>
<system.web>

基于上述代码片段,您正在使用MVC的表单身份验证

当使用表单身份验证时,每当需要身份验证时,ASP.NET框架都会检查当前的IPrinciple类型对象。此IPrinciple类型对象中包含的用户ID和角色将确定是否允许该用户访问

到目前为止,您还没有编写代码来在这个principle对象中推送用户的角色详细信息。为此,您需要在global.asax中重写名为FormsAuthentication_OnAuthenticate的方法。每次ASP.NET framework尝试检查与当前原则相关的身份验证和授权时,都会调用此方法

现在需要做的是重写此方法。检查身份验证票证,因为已验证用户并创建了票证,然后在IPrinciple类型对象中提供此用户/角色信息。为了保持简单,您只需创建一个GenericPriciple对象并在其中设置用户特定的详细信息,如下所示:

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string roles = string.Empty;

                using (userDbEntities entities = new userDbEntities())
                {
                    User user = entities.Users.SingleOrDefault(u => u.username == username);

                    roles = user.Roles;
                }
                //let us extract the roles from our own custom cookie


                //Let us set the Pricipal with our user specific details
                e.User = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
}
注意:在MVC4及更高版本中,此事件将不起作用。为了使自定义表单身份验证在MVC4及更高版本中工作,我们需要将此代码放入Global.asax文件中的Application_PostAuthenticateRequest事件中

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string roles = string.Empty;

                using (userDbEntities entities = new userDbEntities())
                {
                    User user = entities.Users.SingleOrDefault(u => u.username == username);

                    roles = user.Roles;
                }
                //let us extract the roles from our own custom cookie


                //Let us set the Pricipal with our user specific details
                HttpContext.Current.User  = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
} 

参考资料:

您正在验证的用户是管理员用户吗?另外,您如何处理在代码中创建的新属性?创建这样的方法看起来有点奇怪…@Chris:我正在尝试在登录时设置名称,以便可以使用它来检查该方法是否经过授权/@Chris:yes adminuser@Chris:开始database@Stacky看下面的答案,他们应该能解决你的问题。您需要做的是将IPrinciple对象分配给您的用户。在操作中使用[Authorize]属性筛选授权请求
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string roles = string.Empty;

                using (userDbEntities entities = new userDbEntities())
                {
                    User user = entities.Users.SingleOrDefault(u => u.username == username);

                    roles = user.Roles;
                }
                //let us extract the roles from our own custom cookie


                //Let us set the Pricipal with our user specific details
                HttpContext.Current.User  = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
}