mvc

时间:2015-10-01 09:14:02

标签: asp.net-mvc asp.net-mvc-4 authentication

我有一个有两个区域的MVC项目:Admin和Client。我在主控制器中也有一个登录页面。我想要做的是根据用户身份验证用户。如果用户是客户端,则无法登录管理员,反之亦然。 例如,如果您尝试使用Localhost / admin,则代码会检查用户是否已获得授权。如果没有,它会将您重定向到Localhost / admin / AccountLogin。 Localhost / client与Localhost / client / account / login相同。 我想使用customAuthorize而不是[Authorize(Roles =“Admin”)]。

如果我不使用角色,一切正常,但问题是如果您以客户端身份登录,您只需更改网址并转到管理员。所以我尝试使用角色。

在管理区域: 帐户控制器:     public class AccountController:MainProject.Controllers.AccountController     {}

家庭控制器:

[CustomAuthorize("Admin")]
public class HomeController : Controller
{

    public ActionResult HomePage()
    {
        return View();
    }
}

自定义授权:

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private string _loginPage { get; set; }
        private string _customRole { get; set; }

        public CustomAuthorizeAttribute(string userProfilesRequired)
        {
            _customRole = userProfilesRequired;
            _loginPage = "/" + _customRole + "/Account/Login";
        }


        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var formsIdentity = filterContext.HttpContext.User.Identity as System.Web.Security.FormsIdentity;

// I want to check if the role of current user is the same as the controller If not redirect to the /account/login page.

            var validRole = this.Roles == _customRole;//filterContext.HttpContext.User.IsInRole(_customRole);


            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
               if (!validRole)
               {
                   filterContext.HttpContext.Response.Redirect(_loginPage);
               }
            }
            else
            {
                filterContext.HttpContext.Response.Redirect(_loginPage);
            }

            base.OnAuthorization(filterContext);


        }
    }

主控制器中的帐户控制器:

public class AccountController : Controller
{
    [AllowAnonymous]
    public ActionResult Login()
    {
        return View();
    }

    //
    // POST: /Account/Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string ReturnUrl)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (model.UserName == "Arash" && model.Password == "123")
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    //I need to set the roles here but not sure how
                    return RedirectToAction("homePage", "Home", new { area = GetArea() });

                }
            }

            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", "Error: " + ex.Message);
            return View(model);
        }
    }

}

它是网络配置:

  <forms loginUrl="~/Account/Login"  timeout="200"  />
</authentication>

<authorization>
  <allow roles="Admin,Client" />
</authorization>

我在网上搜索了很多但找不到合适的答案。如果您能帮助我在MVC中正确实现此授权,我将不胜感激。

我只是想知道如何在登录时为用户设置角色。目前,如果我在登录时设置用户,则无法记住何时进入CustomAuthorize类。

有任何帮助吗? 欢呼声,

2 个答案:

答案 0 :(得分:1)

我有一个操作方法,只能由管理员访问

    // Action Methods 
    [AuthorizationService]  // My custom filter ,you can apply at controller level
    public ActionResult ProjectList(Employee emp)
    {
      // do some work

    }
 //Employee class
   public class Employee
   {
      string Name{get;set;}
      string Role{get;set;}
  }
  // My custom filter 
   class AuthorizationService : ActionFilterAttribute
      {
         public override void OnActionExecuting(ActionExecutingContext filterContext)
         {
           Employee = filterContext.ActionParameters["emp"] as Employee;
           if (Employee.Role!="Admin")
           {
             filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                 new { action = "Login", Controller ="Home"}));
           }

       }
   }

答案 1 :(得分:1)

有很多方法,但我会告诉你我在这种情况下使用了什么。

您实际上并不需要创建自定义授权属性,而是在PostAuthenticateRequest中使用Global.asax事件处理程序,因为您有&#34;表&#34;数据库中的角色。

Global.asax

中添加以下代码
public override void Init()
{
    this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
                        base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated && User.Identity.AuthenticationType == "Forms")
    {
        string[] roles = GetRoleOfUser(Context.User.Identity.Name);
        var newUser = new GenericPrincipal(Context.User.Identity, roles);
        Context.User = Thread.CurrentPrincipal = newUser;

    }
}

public string[] GetRoleOfUser(string username)
{
    string[] usersInRole;
    // Get the Role of User from the Database
    // Should be of String Array
    // Example Query to Database: 'Select UserRole FROM User WHERE Username = "arash"'
    // It doesnt matter if user has One or more Role.

    return usersInRole;
}

然后你的帐户管理员应该是这个。

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string ReturnUrl)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (model.UserName == "Arash" && model.Password == "123")
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

                    return RedirectToAction("HomePage", "Home");

                }
            }

            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", "Error: " + ex.Message);
            return View(model);
        }
    }

现在举例来说,HomeController中有一个只能由Admin访问的Action。您可以使用Authorize属性装饰操作,如下所示。

HomeController.cs

[Authorize(Roles = "Admin")]
public ActionResult AdminHomepage()
{
    //For Admin Only
    return View();
}

[Authorize(Roles = "Client")]
public ActionResult ClientHomepage()
{
    //Client only Homepage, User with Role "Admin" cant go here.
    return View();
}

[AllowAnonymous]
public ActionResult HomePageForAll()
{
    //For Everyone
    return View();
}

[Authorize(Roles = "Client,Admin")]
public ActionResult HomePageForClientAndAdmin()
{
    return View();
}

public ActionResult HomePage()
{
    return View();
}

如果未经授权,用户将被重定向到登录URL,因为它已在Web.config(已设置)中指定。