4

ASP.NET MVCアプリで、カスタムHttpContent.Userオブジェクトを作成しようとしています。私は、IPrincioalを実装するMemberクラスを作成することから始めました。

public class Member : IPrincipal
{
    public string Id { get; set; }
    public IIdentity Identity { get; set; }
    public bool IsInRole(string role) { throw new NotImplementedException(); }
    ...
}

次に、認証時にHttpContext.UserをMemberクラスのインスタンスに設定します。

FormsAuthentication.SetAuthCookie(email, false);
HttpContext.User = member;

次に、次のように、ユーザーが認証されているかどうかを確認します。

if (User.Identity.IsAuthenticated) { ... }

それは私が立ち往生しているところです。メンバーのインスタンスのプロパティに対して何をする必要があるのか​​わかりません。public IIdentity IdentityHttpContext.Userオブジェクトを次のように使用できるようにします。

IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
ViewBag.IsAuthenticated = IsAuthenticated;

if (IsAuthenticated) {
    CurrentMember = (Member)HttpContext.User;
    ViewBag.CurrentMember = CurrentMember;
}
4

1 に答える 1

6

プリンシパルは、認証 Cookie を書き込むときに一度だけ設定して、後で忘れることができるものではありません。後続のリクエストでは、認証 Cookie が読み取られ、アクション メソッドを実行する前にIPrincipal/が再構築されます。その場合、をカスタムタイプIIdentityにキャストしようとすると、例外がスローされます。HttpContext.UserMember

1 つのオプションは、 でインターセプトしActionFilter、標準の実装をラップするだけです。

public class UsesCustomPrincipalAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var systemPrincipal = filterContext.HttpContext.User;
        var customPrincipal = new Member(systemPrincipal)
        {
            Id = "not sure where this comes from",
        };
        filterContext.HttpContext.User = customPrincipal;
    }
}

public class Member : IPrincipal
{
    private readonly IPrincipal _systemPrincipal;

    public Member(IPrincipal principal)
    {
        if (principal == null) throw new ArgumentNullException("principal");
        _systemPrincipal = principal;
    }

    public string Id { get; set; }

    public IIdentity Identity { get { return _systemPrincipal.Identity; } }

    public bool IsInRole(string role)
    {
        return _systemPrincipal.IsInRole(role);
    }
}

IPrincipalこのようにして、デフォルトとIIdentity実装ですぐに使えるものを失うことはありません。IsAuthenticatedIIdentity、または で呼び出すこともできIsInRole(string)ますIPrincipalId得られる唯一のものは、カスタム実装の余分なプロパティIPrincipalです (ただし、これがどこから来たのか、なぜ必要なのかはわかりません)。

于 2012-08-11T10:44:44.010 に答える