如何在 MVC 中为自定义用户对象实现 IIdentity ASP.NET



在我的 ASP.NET MVC应用程序中,我正在尝试创建自定义的HttpContent.User对象。我首先创建了一个 Member 类,它实现了 IPincioal。

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 Identity属性做什么。这样我就可以使用 HttpContext.User 对象

,如下所示:
IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
ViewBag.IsAuthenticated = IsAuthenticated;
if (IsAuthenticated) {
    CurrentMember = (Member)HttpContext.User;
    ViewBag.CurrentMember = CurrentMember;
}

主体不是你可以在编写身份验证 cookie 时设置一次然后以后忘记的东西。在后续请求期间,在执行操作方法之前,将读取身份验证cookie并重建IPrincipal/IIdentity。发生这种情况时,尝试将HttpContext.User强制转换为自定义Member类型将引发异常。

一种选择是在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);
    }
}

这样,您就不会丢失默认IPrincipalIIdentity实现的现成内容。您仍然可以在IIdentity上调用IsAuthenticated,甚至可以在IPrincipal上调用IsInRole(string)。您唯一获得的是自定义IPrincipal实现上的额外Id属性(尽管我不确定这是从哪里来的或为什么需要它)。

最新更新