3

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

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

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

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

我一直在尝试用 MVC2 应用程序中的 IIdentity、IPrincipal 和 Role 授权来围绕安全程序流进行思考——但我在这里真的很挣扎,可以使用一些指导。互联网上有大量关于部分的文章,但关于整体的文章不多。

编辑

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

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;
  }

    }
4

1 回答 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]属性装饰你的基本控制器。

于 2011-01-21T09:15:39.833 回答