6

Authorize属性をロールで機能させるのに問題があります。これは、コントローラーをどのように装飾したかです。

[Authorize(Roles = "admin")]
public ActionResult Index()
{
    ...
}

これがユーザーのログイン方法です。

string roles = "admin";
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
    1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    false,
    roles
);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
HttpContext.Current.Response.Cookies.Add(cookie);

しかし、私のユーザーはまだアクセスを拒否されています。どこが間違っていますか?

4

1 に答える 1

8

私はあなたのコードの同様の例に出くわしました: MVCの最も投票数の多い回答- How to store/assign roles of authenticated users 。

AuthorizeAttribute は、HttpContext.Userに格納されているIPrincipalインスタンスでIsInRoleメソッドを呼び出します。デフォルトでは、IPrincipal にはロールがありません。この場合、IsInRole は常に false を返します。これが、アクションへのアクセスが拒否される理由です。

ユーザーのロールをFormsAuthenticationTicket の UserData プロパティに保存したので、自分で認証 Cookie から IPrincipal インスタンスにロールを抽出する必要があります。MVCの最も投票された回答- 認証されたユーザーのロールを保存/割り当てる方法は、これを行うために global.asax.cs ファイルに直接追加できるコードを提供します。私はそれを以下に繰り返しました:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
      FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
      string[] roles = authTicket.UserData.Split(',');
      GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
      Context.User = userPrincipal;
    }
}
于 2013-09-15T05:05:18.513 に答える