2017-07-28 11 views
0

を働いていません。MVCをFormsAuthentication IsInRoleは、私は、ユーザーを認証しています

ただし、私のビュー(_layout)には次のものがあり、管理者の確認は失敗します。

if (ViewContext.HttpContext.User.IsInRole("Administrator")) 
{ 
    <li class="dropdown"> 
... 

私が見るには、「IsInRole」を理解することができるようにするために必要なものはありますか?

これは動作します:

@if (ViewContext.HttpContext.User.Identity.IsAuthenticated == false) 

しかし、 'IsInRole'

は常にfalseと評価されました。自分でをFormsAuthenticationクッキーを設定しているので

答えて

1

、あなたは原則オブジェクトを作成し、たAuthenticateRequestイベント内のすべての要求に応じて現在のスレッドに割り当てる必要があります。

Global.asax.cs

public class Global : HttpApplication 
{ 
    protected void Application_AuthenticateRequest(object sender, EventArgs e) 
    { 
     HttpCookie decryptedCookie = 
      Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     if (decryptedCookie != null) 
     { 
      FormsAuthenticationTicket ticket = 
       FormsAuthentication.Decrypt(decryptedCookie.Value); 

      var identity = new GenericIdentity(ticket.Name); 
      var roles = ticket.UserData.Split(','); 
      var principal = new GenericPrincipal(identity, roles); 

      HttpContext.Current.User = principal; 
      Thread.CurrentPrincipal = HttpContext.Current.User; 
     } 
    } 
} 

サインイン方法

public void SignIn(string username, bool createPersistentCookie) 
{ 
    var now = DateTime.UtcNow.ToLocalTime(); 
    TimeSpan expirationTimeSpan = FormsAuthentication.Timeout; 

    var ticket = new FormsAuthenticationTicket(
     1 /*version*/, 
     username, 
     now, 
     now.Add(expirationTimeSpan), 
     createPersistentCookie, 
     "" /*userData*/, 
     FormsAuthentication.FormsCookiePath); 

    var encryptedTicket = FormsAuthentication.Encrypt(ticket); 

    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
     encryptedTicket) 
    { 
     HttpOnly = true, 
     Secure = FormsAuthentication.RequireSSL, 
     Path = FormsAuthentication.FormsCookiePath 
    }; 

    if (ticket.IsPersistent) 
    { 
     cookie.Expires = ticket.Expiration; 
    } 
    if (FormsAuthentication.CookieDomain != null) 
    { 
     cookie.Domain = FormsAuthentication.CookieDomain; 
    } 

    Response.Cookies.Add(cookie); 
} 
+0

おかげで、これは私がみます何かのように聞こえます。私は間違った方法でクッキーを設定していますか?これを達成するより良い方法はありますか? – Craig

+0

私は各認証のデータベースから自分の役割を取得する必要があるようですが、その方法はそれが見える各ビューに対して起動します。 – Craig

+1

すべての要求に対してデータを照会しないように、UserData内にロールを保存する必要があります。私は答えを更新しました。 – Win

関連する問題