如何使用ASP.NET MVC 4中的数据库用户列表在控制器操作中授权用户?

时间:2015-04-20 16:26:52

标签: asp.net asp.net-mvc

我这样做是为了授权用户。

[Authorize(Users = @"user1, user2, user3")]
public class MyController : Controller
  {
      // my stuff
  }

我想从数据库表中的用户列表中进行授权..

2 个答案:

答案 0 :(得分:0)

这是我完成的方式:

创建一个新类(继承自AuthorizeAttribute类)。

public class CustomAuthorizeAttribute : AuthorizeAttribute

重写AuthorizeCore方法(在CustomAuthorizeAttribute类中),并在其中包含您的自定义逻辑。

protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isUserAuthorized = false;
            // custom logic goes here
            // You can get the details of the user making the call using httpContext
            // (httpContext.User.Identity.Name)
            // Then get the information you have stored on your db, and compare it 
            // with these details.
            // Set isUserAuthorized to true if the values match

            return isUserAuthorized;
        }

使用刚创建的属性装饰控制器操作方法。

[CustomAuthorize]
public ActionResult DoSomething(string something, string someOtherThing)

答案 1 :(得分:-2)

此链接表格Gotalove很有帮助。 尝试以下方法:

"使用@VikasRana http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF分享的链接

我摆脱了我的枚举角色和方法

public CustomAuthorizeAttribute(params object[] roles)
{ ...}

然后我将模型中的角色更改为字符串,例如User.Role ="联系"而不是int。在我的onAuthorization方法中,我将其更改为:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    base.OnAuthorization(filterContext);
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
        filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
        filterContext.Result = new RedirectResult("~/User/Login");
        return;
    }
    if (filterContext.Result is HttpUnauthorizedResult)
    {
        filterContext.Controller.TempData["ErrorDetails"] = "You don't have access rights to this page";
        filterContext.Result = new RedirectResult("~/User/Login");
        return;
    }
    }

并在我的global.asax中添加了这个。

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true && Request.IsAuthenticated== 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 (GManagerDBEntities db = new GManagerDBEntities())
                {
                    User user = db.Users.SingleOrDefault(u => u.Username == username);

                    roles = user.Role;
                }
                //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)
            {
                //something went wrong
            }
        }
    }
}   

"

来源:Custom user authorization based with roles in asp.net mvc

PS。:在这个链接中,在同一篇文章中,有第二种方法来解决您的问题。 在帖子的底部。

如果这不能帮到你,你应该尝试一下。