、あなたは原則オブジェクトを作成し、た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);
}
出典
2017-07-29 00:03:28
Win
おかげで、これは私がみます何かのように聞こえます。私は間違った方法でクッキーを設定していますか?これを達成するより良い方法はありますか? – Craig
私は各認証のデータベースから自分の役割を取得する必要があるようですが、その方法はそれが見える各ビューに対して起動します。 – Craig
すべての要求に対してデータを照会しないように、UserData内にロールを保存する必要があります。私は答えを更新しました。 – Win