加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在ASP.NET MVC中为自定义User对象实现IIdent

发布时间:2020-12-16 06:47:47 所属栏目:asp.Net 来源:网络整理
导读:在我的ASP.NET MVC应用程序中,我正在尝试创建一个自定义的HttpContent.User对象.我首先创建了一个实现IPrincioal的Member类. public class Member : IPrincipal{ public string Id { get; set; } public IIdentity Identity { get; set; } public bool IsInR
在我的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) { ... }

那就是我被困住的地方.我不确定我需要为会员实例上的公共IIdentity Identity属性做些什么.这样我就可以使用像这样的HttpContext.User对象:

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

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

解决方法

在编写auth cookie时,Principal不是你可以设置的东西而是稍后忘记.在后续请求期间,读取auth cookie并在执行动作方法之前重建IPrincipal / IIdentity.当发生这种情况时,尝试将HttpContext.User强制转换为自定义成员类型将引发异常.

一种选择是在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实现的开箱即用的东西.您仍然可以在IIdentity上调用IsAuthenticated,甚至可以在IPrincipal上调用IsInRole(字符串).您唯一获得的是自定义IPrincipal实现的额外Id属性(虽然我不确定它来自何处或为什么需要它).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读