1

そのため、現在、ログインに設定された ViewBag を使用して、管理者のみのものを表示できるかどうかを判断しています。これは、ModelFirst ASP.net を使用しているため、Roles.CreateRole、Membership.CreateUser、および Roles.AddUserToRole が無効になっているためです。

public ActionResult Login(LoginModel model, string returnUrl)
    {
        ViewBag.Admin = false;
            if (model.IsValid(model.UserName, model.Password))
            {
                ViewBag.Admin = (bool)model.currentLoggedInEmployee.IsAdmin;
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Login data is incorrect!");
                return View(model);
            }
    }

次に、単純に次を使用します。

   @if (ViewBag.Admin == true) {
        <li>@Html.ActionLink("Administration", "Index", "Administration")</li>
   }

これらのボタンを管理者にのみ表示します。これは機能します。

ここで私たちが望むのは、通常の

[Authenticate(Roles="Admin")]
[HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        // TODO: Add insert logic here
    }

しかし、「ロール」がないため、このようにすることはできません。ViewBag.Admin 値を使用して、ユーザーがこれらの機能を使用できるようにする必要があります。問題は、これをどのように行うことができるかということです。

4

1 に答える 1

1

独自のAuthorizeAttributeを展開することをお勧めします。そこから、現在ログインしているユーザーが管理者であるかどうかを判断できます。

認証 Cookie を作成するときに、いくつかの追加情報 (つまり、管理者フラグ) を追加します。

public ActionResult Login(LoginModel model, string returnUrl)
{
    if (model.IsValid(model.UserName, model.Password))
    {
         var ticket = new FormsAuthenticationTicket(1,
             model.UserName,
             DateTime.Now,
             DateTime.Now.AddMinutes(30),
             model.RememberMe,
             model.currentLoggedInEmployee.IsAdmin, // user data
             FormsAuthentication.FormsCookiePath);

         // Encrypt the ticket.
         string encTicket = FormsAuthentication.Encrypt(ticket);

         // Create the cookie.
         Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

         // Redirect back to original URL.
         return RedirectToAction("Index", "Home");
    }
    else
    {
        ModelState.AddModelError("", "Login data is incorrect!");
        return View(model);
    }
}

ログインしているユーザーをロールに対して認証するためのカスタム承認属性を作成します。

public class AdminOnlyAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Current.User.Identity.IsAuthenticated)
        {
            var ticket = ((FormsIdentity)User.Identity).Ticket;
            return (bool)ticket.UserData;
        }
        else
        {
             return false;
        }
    }
}

次に、アクションを次のように装飾します。

[AdminOnly]
[HttpPost]
public ActionResult Create(FormCollection collection)
{
    // TODO: add insert logic here
}
于 2013-05-08T11:49:27.197 に答える