【问题标题】:MVC2 :: How do I *USE* a Custom IIdentity Class?MVC2 :: 我如何*使用*自定义 IIdentity 类?
【发布时间】:2011-06-12 19:52:50
【问题描述】:

我正在尝试从网络服务中存储有关用户的大量信息。由于这是有关当前经过身份验证的用户的信息,因此我认为将这些信息存储在自定义 IIdentity 实现中是有意义的。

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

自定义会员提供者和自定义会员用户都可以正常工作。

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

我一直试图在 MVC2 应用程序中使用 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;
  }

    }

【问题讨论】:

    标签: security asp.net-mvc-2 authorization iprincipal iidentity


    【解决方案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] 属性装饰你的基本控制器。

    【讨论】:

    • 我注意到 _provider 没有实例化 - 为什么会这样?
    • @ScottSEA,这个_provider 变量可以是任何允许您检索经过身份验证的用户信息的变量。
    • 那么用这种方法在这里实例化它会安全吗? ...由于某种原因,我收到一条错误消息,提示 AuthorizeCore(HttpContextBase httpContext)“没有找到合适的方法来覆盖”
    • 这很奇怪。我不知道。如果您在 AuthorizeAttribute 上按 F12,您会看到该方法吗?
    • 经过一番搜索,我发现这可能与我在类库项目中拥有 MagicAuthorizeAttribute 类这一事实有关(我正在尝试使该功能在整个公司中可重用) - 但我不知道如何解决它。我确实有一个用于 System.Web 和 System.Web.Mvc 的 using 指令 - 当我键入“覆盖”时,智能感知会弹出一个 AuthorizeAttribute 方法框供我选择。 (我使用的是 .net 4.0 框架)
    猜你喜欢
    • 2012-05-31
    • 2021-07-09
    • 2010-11-07
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多