マシューが言うように、プリンシパルを構築し、適切なタイミングで自分で設定することは、SiteMapのような組み込みのロールベースの機能をすべて利用する最も簡単な方法です。
しかし、MSDNで示されているよりも、これを実装するためのはるかに簡単な標準ベースの方法があります。
これは私が単純な役割プロバイダーを実装する方法です
Global.asax
using System;
using System.Collections.Specialized;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Security;
namespace SimpleRoles
{
public class Global : HttpApplication
{
private static readonly NameValueCollection Roles =
new NameValueCollection(StringComparer.InvariantCultureIgnoreCase)
{
{"administrator", "admins"},
// note, a user can be in more than one role
{"administrator", "codePoets"},
};
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
Context.User = Thread.CurrentPrincipal =
new GenericPrincipal(Context.User.Identity, Roles.GetValues(ticket.Name));
}
}
}
}
ページコードビハインドのコンテキストでユーザーを手動でチェックするには:
if (User.IsInRole("admins"))
{
// allow something
}
他の場所では、ユーザーを現在のコンテキストから解放します
if (HttpContext.Current.User.IsInRole("admins"))
{
// allow something
}