以下に示すように、独自の実装を作成しIPrincipal
ます。IIdentity
[ComVisible(true)]
[Serializable]
public sealed class CustomIdentity : IIdentity {
private readonly string _name;
private readonly string _email;
// and other stuffs
public CustomIdentity(string name) {
_name = name.Trim();
if(string.IsNullOrWhiteSpace(name))
return;
_email = (connect to database and read email and other stuffs);
}
public string Name {
get { return _name; }
}
public string Email {
get { return _email; }
}
public string AuthenticationType {
get { return "CustomIdentity"; }
}
public bool IsAuthenticated {
get { return !string.IsNullOrWhiteSpace(_name); }
}
}
[ComVisible(true)]
[Serializable]
public sealed class CustomPrincipal : IPrincipal {
private readonly CustomIdentity _identity;
public CustomPrincipal(CustomIdentity identity) {
_identity = identity;
}
public bool IsInRole(string role) {
return _identity != null &&
_identity.IsAuthenticated &&
!string.IsNullOrWhiteSpace(role) &&
Roles.IsUserInRole(_identity.Name, role);
}
IIdentity IPrincipal.Identity {
get { return _identity; }
}
public CustomIdentity Identity {
get { return _identity; }
}
}
また、私は を作成しHttpModule
、そのAuthenticateRequest
イベントでこれを行います:
public void Init(HttpApplication context) {
_application = context;
_application.AuthenticateRequest += ApplicationAuthenticateRequest;
}
private void ApplicationAuthenticateRequest(object sender, EventArgs e) {
var formsCookie = _application.Request.Cookies[FormsAuthentication.FormsCookieName];
var identity = formsCookie != null
? new CustomIdentity(FormsAuthentication.Decrypt(formsCookie.Value).Name)
: new CustomIdentity(string.Empty);
var principal = new CustomPrincipal(identity);
_application.Context.User = Thread.CurrentPrincipal = principal;
}
また、私は自分自身を作成し、Controller
これらWebViewPage
が好きです:
public abstract class CustomController : Controller {
public new CustomPrincipal User {
get {
var user = System.Web.HttpContext.Current.User as CustomPrincipal;
return user;
}
}
}
public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> {
public new CustomPrincipal User {
get {
// (Place number 1) here is the error I'm speaking about!!!
var user = HttpContext.Current.User as CustomPrincipal;
return user;
}
}
}
上記のコードに示されているように、すべてが正しいようです。しかし、ご覧のとおり、場所番号 1CustomPrincipal
では!にアクセスできません。RolePrincipal
この場所では、私は の代わりに を持っていることを意味しCustomPrincipal
ます。例えばHttpContext.Current.User
は のRolePrincipal
代わりに ですCustomPrincipal
。しかし、RolePrincipal.Identity
プロパティはCustomIdentity
!