首页 文章

MVC2 ::我如何*使用*自定义IIdentity类?

提问于
浏览
3

我试图从Web服务存储一整套关于用户的信息 . 由于这是有关当前经过身份验证的用户的信息,我认为将该信息存储在自定义IIdentity实现中是有意义的 .

自定义 MagicMembershipProvider.GetUser(string id, bool userIsOnline) 调用webservice并返回一个 MagicMembershipUser 实例,其中填充了所有字段(部门,电话号码,其他员工信息) .

自定义成员资格提供程序和自定义成员资格用户都可正

What and where is the best way to put the membership user information into the IPrincipal User object that is accessible in every controller?

我一直试图用MVID2应用程序中的IIdentity,IPrincipal和Role授权来围绕安全程序流程 - 但我真的在这里苦苦挣扎,可以使用一些指导 . 有一篇关于这些部分的文章,但关于整体的文章并不多 .

编辑

到目前为止,我最好的猜测是在 FormsAuthenticationService 中分配 HttpContext.Current.User

public void SignIn(string userName, bool createPersistentCookie)
{
  if (String.IsNullOrEmpty(userName)) 
    throw new ArgumentException("Value cannot be null or empty.", "userName");

  try
  {
    FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    MagicMembershipUser magicUser = _provider.GetUser("", false) 
      as MagicMembershipUser;
    MagicIdentity identity = new MagicIdentity(userName, magicUser);
    GenericPrincipal principal = new GenericPrincipal(identity, null);

    HttpContext.Current.User = principal;
  }
  catch (Exception)
  {
    throw;
  }

    }

1 回答

  • 1

    将会员用户信息放入每个控制器可访问的IPrincipal User对象的最佳方式是什么?

    在自定义[Authorize]过滤器实现中 . 您可以覆盖AuthorizeCore方法并调用基本方法,如果它返回true,则查询您的成员资格提供程序并将自定义魔术身份注入上下文 .

    例:

    public class MagicAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (isAuthorized)
            {
                var username = httpContext.User.Identity.Name;
                var magicUser = _provider.GetUser(username, false) as MagicMembershipUser;
                var identity = new MagicIdentity(username, magicUser);
                var principal = new GenericPrincipal(identity, null);
                httpContext.User = principal;
            }
            return isAuthorized;
        }
    }
    

    现在剩下的就是使用 [MagicAuthorize] 属性装饰你的基本控制器 .

相关问题