【问题标题】:ASP.NET MVC - Set custom IIdentity or IPrincipalASP.NET MVC - 设置自定义 IIdentity 或 IPrincipal
【发布时间】:2010-11-07 01:09:50
【问题描述】:

我需要做一些相当简单的事情:在我的 ASP.NET MVC 应用程序中,我想设置一个自定义的 IIdentity / IPrincipal。哪个更容易/更合适。我想扩展默认值,以便可以调用User.Identity.IdUser.Identity.Role 之类的名称。没什么特别的,只是一些额外的属性。

我已经阅读了大量文章和问题,但我觉得我做的比实际更难。我以为这很容易。如果用户登录,我想设置一个自定义 IIdentity。所以我想,我将在我的 global.asax 中实现Application_PostAuthenticateRequest。但是,在每个请求上都会调用它,我不想在每个请求上调用数据库,因为它会从数据库中请求所有数据并放入自定义 IPrincipal 对象。这似乎也非常不必要,缓慢且在错误的地方(在那里进行数据库调用),但我可能是错的。或者这些数据还来自哪里?

所以我想,每当用户登录时,我都可以在我的会话中添加一些必要的变量,我将这些变量添加到 Application_PostAuthenticateRequest 事件处理程序中的自定义 IIdentity 中。但是,我的Context.Sessionnull 那里,所以这也不是要走的路。

我已经为此工作了一天,我觉得我错过了一些东西。这应该不难做到,对吧?我也对随之而来的所有(半)相关的东西有点困惑。 MembershipProviderMembershipUserRoleProviderProfileProviderIPrincipalIIdentityFormsAuthentication.... 是不是只有我一个人觉得这一切很混乱?

如果有人能告诉我一个简单、优雅且高效的解决方案,可以在 IIdentity 上存储一些额外的数据,而不会产生任何额外的模糊......那就太好了!我知道在 SO 上有类似的问题,但如果我需要的答案在那里,我一定忽略了。

【问题讨论】:

  • 您好 Domi,它是仅存储永不更改的数据(如用户 ID)或在用户更改必须立即反映在 cookie 中的数据后直接更新 cookie 的组合。如果用户这样做,我只需使用新数据更新 cookie。但我尽量不存储经常变化的数据。
  • 这个问题有 36k 浏览量和很多点赞。这真的是一个普遍的要求吗?如果是这样,难道没有比所有这些“定制的东西”更好的方法吗?
  • @Simon_Weaver 有 ASP.NET Identity 知道,它更容易支持加密 cookie 中的附加自定义信息。
  • 我同意你的观点,有很多像你一样的信息:MemberShip...PrincipalIdentity。 ASP.NET 应该使这更容易、更简单,并且最多有两种处理身份验证的方法。
  • @Simon_Weaver 这清楚地表明需要更简单、更灵活的身份系统恕我直言。

标签: asp.net asp.net-mvc forms-authentication iprincipal iidentity


【解决方案1】:

我是这样做的。

我决定使用 IPrincipal 而不是 IIdentity,因为这意味着我不必同时实现 IIdentity 和 IPrincipal。

  1. 创建界面

    interface ICustomPrincipal : IPrincipal
    {
        int Id { get; set; }
        string FirstName { get; set; }
        string LastName { get; set; }
    }
    
  2. 自定义主体

    public class CustomPrincipal : ICustomPrincipal
    {
        public IIdentity Identity { get; private set; }
        public bool IsInRole(string role) { return false; }
    
        public CustomPrincipal(string email)
        {
            this.Identity = new GenericIdentity(email);
        }
    
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
  3. CustomPrincipalSerializeModel - 用于将自定义信息序列化到 FormsAuthenticationTicket 对象中的 userdata 字段中。

    public class CustomPrincipalSerializeModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
  4. LogIn 方法 - 使用自定义信息设置 cookie

    if (Membership.ValidateUser(viewModel.Email, viewModel.Password))
    {
        var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();
    
        CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
        serializeModel.Id = user.Id;
        serializeModel.FirstName = user.FirstName;
        serializeModel.LastName = user.LastName;
    
        JavaScriptSerializer serializer = new JavaScriptSerializer();
    
        string userData = serializer.Serialize(serializeModel);
    
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                 1,
                 viewModel.Email,
                 DateTime.Now,
                 DateTime.Now.AddMinutes(15),
                 false,
                 userData);
    
        string encTicket = FormsAuthentication.Encrypt(authTicket);
        HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        Response.Cookies.Add(faCookie);
    
        return RedirectToAction("Index", "Home");
    }
    
  5. Global.asax.cs - 读取 cookie 并替换 HttpContext.User 对象,这是通过覆盖 PostAuthenticateRequest 来完成的

    protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    
            JavaScriptSerializer serializer = new JavaScriptSerializer();
    
            CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
    
            CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
            newUser.Id = serializeModel.Id;
            newUser.FirstName = serializeModel.FirstName;
            newUser.LastName = serializeModel.LastName;
    
            HttpContext.Current.User = newUser;
        }
    }
    
  6. 在 Razor 视图中访问

    @((User as CustomPrincipal).Id)
    @((User as CustomPrincipal).FirstName)
    @((User as CustomPrincipal).LastName)
    

在代码中:

    (User as CustomPrincipal).Id
    (User as CustomPrincipal).FirstName
    (User as CustomPrincipal).LastName

我认为代码是不言自明的。如果不是,请告诉我。

此外,为了使访问更容易,您可以创建一个基本控制器并覆盖返回的用户对象 (HttpContext.User):

public class BaseController : Controller
{
    protected virtual new CustomPrincipal User
    {
        get { return HttpContext.User as CustomPrincipal; }
    }
}

然后,对于每个控制器:

public class AccountController : BaseController
{
    // ...
}

这将允许您访问代码中的自定义字段,如下所示:

User.Id
User.FirstName
User.LastName

但这在视图中不起作用。为此,您需要创建一个自定义 WebViewPage 实现:

public abstract class BaseViewPage : WebViewPage
{
    public virtual new CustomPrincipal User
    {
        get { return base.User as CustomPrincipal; }
    }
}

public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
    public virtual new CustomPrincipal User
    {
        get { return base.User as CustomPrincipal; }
    }
}

将其设为 Views/web.config 中的默认页面类型:

<pages pageBaseType="Your.Namespace.BaseViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>

在视图中,您可以像这样访问它:

@User.FirstName
@User.LastName

【讨论】:

  • 很好的实现;注意 RoleManagerModule 用 RolePrincipal 替换您的自定义主体。这让我很痛苦 - stackoverflow.com/questions/10742259/…
  • 好的,我找到了解决方案,只需添加一个 else 开关,将“”(空字符串)作为电子邮件传递,身份将是匿名的。
  • DateTime.Now.AddMinutes(N)... 如何做到这一点,这样它就不会在 N 分钟后注销用户,是否可以保留已登录的用户(当用户检查“记住我”时例子)?
  • 如果您使用 WebApiController,则需要将 Thread.CurrentPrincipal 设置为 Application_PostAuthenticateRequest 才能使其工作,因为它不依赖于 HttpContext.Current.User
  • @AbhinavGujjar FormsAuthentication.SignOut(); 对我来说很好。
【解决方案2】:

我不能直接说 ASP.NET MVC,但对于 ASP.NET Web 窗体,诀窍是创建一个 FormsAuthenticationTicket 并在用户通过身份验证后将其加密到 cookie 中。这样,您只需调用一次数据库(或 AD 或您用于执行身份验证的任何内容),随后的每个请求都将根据 cookie 中存储的票证进行身份验证。

关于这方面的一篇好文章:http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html(链接断开)

编辑:

由于上面的链接已损坏,我会在上面的答案中推荐 LukeP 的解决方案:https://stackoverflow.com/a/10524305 - 我还建议将接受的答案更改为那个。

编辑 2: 断开链接的替代方法:https://web.archive.org/web/20120422011422/http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html

【讨论】:

  • 来自 PHP,我总是将 UserID 等信息以及授予受限访问权限所需的其他部分放在 Session 中。将它存储在客户端让我很紧张,你能评论一下为什么这不会成为问题吗?
  • @JohnZ - 票证本身在通过网络发送之前已在服务器上加密,因此客户端无法访问票证中存储的数据。请注意,会话 ID 也存储在 cookie 中,因此并没有什么不同。
  • 如果你在这里,你应该看看 LukeP 的解决方案
  • 我一直担心这种方法可能会超过最大 cookie 大小 (stackoverflow.com/questions/8706924/…)。我倾向于使用Cache 作为Session 的替代品,以将数据保存在服务器上。谁能告诉我这是否是一种有缺陷的方法?
  • 不错的方法。这样做的一个潜在问题是,如果您的用户对象具有多个属性(尤其是如果有任何嵌套对象),则一旦加密值超过 4KB(比您想象的更容易命中),创建 cookie 将静默失败。如果您只存储关键数据,那很好,但其余部分您仍然必须点击 DB。另一个考虑是当用户对象有签名或逻辑变化时“升级”cookie数据。
【解决方案3】:

这是完成工作的示例。 bool isValid 是通过查看一些数据存储来设置的(比如说你的用户数据库)。 UserID 只是我维护的一个 ID。您可以向用户数据添加其他信息,例如电子邮件地址。

protected void btnLogin_Click(object sender, EventArgs e)
{         
    //Hard Coded for the moment
    bool isValid=true;
    if (isValid) 
    {
         string userData = String.Empty;
         userData = userData + "UserID=" + userID;
         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), true, userData);
         string encTicket = FormsAuthentication.Encrypt(ticket);
         HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
         Response.Cookies.Add(faCookie);
         //And send the user where they were heading
         string redirectUrl = FormsAuthentication.GetRedirectUrl(username, false);
         Response.Redirect(redirectUrl);
     }
}

在 gobal asax 中添加以下代码以检索您的信息

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[
             FormsAuthentication.FormsCookieName];
    if(authCookie != null)
    {
        //Extract the forms authentication cookie
        FormsAuthenticationTicket authTicket = 
               FormsAuthentication.Decrypt(authCookie.Value);
        // Create an Identity object
        //CustomIdentity implements System.Web.Security.IIdentity
        CustomIdentity id = GetUserIdentity(authTicket.Name);
        //CustomPrincipal implements System.Web.Security.IPrincipal
        CustomPrincipal newUser = new CustomPrincipal();
        Context.User = newUser;
    }
}

当您稍后要使用这些信息时,您可以按如下方式访问您的自定义主体。

(CustomPrincipal)this.User
or 
(CustomPrincipal)this.Context.User

这将允许您访问自定义用户信息。

【讨论】:

  • 仅供参考——它是 Request.Cookies[](复数)
  • 不要忘记将 Thread.CurrentPrincipal 和 Context.User 设置为 CustomPrincipal。
  • GetUserIdentity() 从何而来?
  • 正如我在评论中提到的,它提供了 System.Web.Security.IIdentity 的实现。谷歌关于那个界面
【解决方案4】:

MVC 为您提供了挂在控制器类中的 OnAuthorize 方法。或者,您可以使用自定义操作过滤器来执行授权。 MVC 使它很容易做到。我在这里发布了一篇关于此的博客文章。 http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0

【讨论】:

  • 但是会话可能会丢失并且用户仍然进行身份验证。没有?
  • @brady gaster,我阅读了您的博客文章(谢谢!),为什么有人会使用覆盖“OnAuthorize()”,正如您在 global.asax 条目中提到的那样,“...AuthenticateRequest( ..)”其他答案提到的?在设置主要用户时,一个优先于另一个?
【解决方案5】:

如果您需要将一些方法连接到 @User 以在您的视图中使用,这里有一个解决方案。没有任何严肃的会员定制的解决方案,但如果原始问题只需要视图,那么这可能就足够了。下面用于检查从授权过滤器返回的变量,用于验证是否要显示某些链接(不适用于任何类型的授权逻辑或访问权限)。

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Security.Principal;

    namespace SomeSite.Web.Helpers
    {
        public static class UserHelpers
        {
            public static bool IsEditor(this IPrincipal user)
            {
                return null; //Do some stuff
            }
        }
    }

然后只需在区域 web.config 中添加一个引用,并在视图中如下所示调用它。

@User.IsEditor()

【讨论】:

  • 在您的解决方案中,我们再次需要每次都进行数据库调用。因为用户对象没有自定义属性。它只有 Name 和 IsAuthanticated
  • 这完全取决于您的实现和所需的行为。我的示例包含 0 行数据库或角色逻辑。如果有人使用 IsInRole,我相信它又可以缓存在 cookie 中。或者您实现自己的缓存逻辑。
【解决方案6】:

LukeP's answer的基础上,增加一些方法来设置timeoutrequireSSL配合Web.config

参考链接

修改代码LukeP

1、根据Web.Config设置timeoutFormsAuthentication.Timeout 将获得超时值,该值在 web.config 中定义。我将以下内容包装成一个函数,它返回一个ticket

int version = 1;
DateTime now = DateTime.Now;

// respect to the `timeout` in Web.config.
TimeSpan timeout = FormsAuthentication.Timeout;
DateTime expire = now.Add(timeout);
bool isPersist = false;

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
     version,          
     name,
     now,
     expire,
     isPersist,
     userData);

2、根据RequireSSL配置,配置cookie是否安全。

HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
// respect to `RequreSSL` in `Web.Config`
bool bSSL = FormsAuthentication.RequireSSL;
faCookie.Secure = bSSL;

【讨论】:

    【解决方案7】:

    好的,所以我在这里是一个严肃的密码管理员,提出了这个非常古老的问题,但是有一个更简单的方法,上面的@Baserz 提到了这一点。那就是使用 C# 扩展方法和缓存的组合(不要使用会话)。

    事实上,微软已经在Microsoft.AspNet.Identity.IdentityExtensions 命名空间中提供了一些这样的扩展。例如,GetUserId() 是一个返回用户 ID 的扩展方法。还有GetUserName()FindFirstValue(),它们根据IPrincipal返回声明。

    所以你只需要包含命名空间,然后调用User.Identity.GetUserName() 来获取 ASP.NET Identity 配置的用户名。

    我不确定这是否被缓存,因为旧的 ASP.NET Identity 不是开源的,我也没有费心对其进行逆向工程。但是,如果不是,那么您可以编写自己的扩展方法,该方法会将此结果缓存特定的时间。

    【讨论】:

    • 为什么“不使用会话”?
    • @jitbit - 因为会话不可靠且不安全。出于同样的原因,您不应该出于安全目的使用会话。
    • “不可靠”可以通过重新填充会话(如果为空)来解决。 “不安全” - 有一些方法可以防止会话劫持(通过仅使用 HTTPS + 其他方式)。但我实际上同意你的看法。那你会在哪里缓存它? IsUserAdministratorUserEmail 等信息?你在想HttpRuntime.Cache
    • @jitbit - 这是一个选项,或者如果你有另一个缓存解决方案。确保在一段时间后使缓存条目过期。不安全也适用于本地系统,因为您可以手动更改 cookie 并猜测会话 ID。中间人不是唯一的问题。
    【解决方案8】:

    作为 Web 表单用户(不是 MVC)的 LukeP 代码的补充,如果您想简化页面背后代码中的访问,只需将以下代码添加到基本页面并在所有页面中派生基本页面:

    Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
        Get
            Return DirectCast(MyBase.User, CustomPrincipal)
        End Get
    End Property
    

    所以在你后面的代码中你可以简单地访问:

    User.FirstName or User.LastName
    

    我在 Web 窗体场景中缺少的是如何在不绑定到页面的代码中获得相同的行为,例如在 httpmodules 中,我是否应该始终在每个类中添加强制转换?有没有更聪明的方法来获得这个?

    感谢您的回答并感谢 LukeP,因为我使用您的示例作为我的自定义用户的基础(现在有 User.RolesUser.TasksUser.HasPath(int)User.Settings.Timeout 和许多其他好东西)

    【讨论】:

      【解决方案9】:

      我尝试了 LukeP 建议的解决方案,发现它不支持 Authorize 属性。所以,我稍微修改了一下。

      public class UserExBusinessInfo
      {
          public int BusinessID { get; set; }
          public string Name { get; set; }
      }
      
      public class UserExInfo
      {
          public IEnumerable<UserExBusinessInfo> BusinessInfo { get; set; }
          public int? CurrentBusinessID { get; set; }
      }
      
      public class PrincipalEx : ClaimsPrincipal
      {
          private readonly UserExInfo userExInfo;
          public UserExInfo UserExInfo => userExInfo;
      
          public PrincipalEx(IPrincipal baseModel, UserExInfo userExInfo)
              : base(baseModel)
          {
              this.userExInfo = userExInfo;
          }
      }
      
      public class PrincipalExSerializeModel
      {
          public UserExInfo UserExInfo { get; set; }
      }
      
      public static class IPrincipalHelpers
      {
          public static UserExInfo ExInfo(this IPrincipal @this) => (@this as PrincipalEx)?.UserExInfo;
      }
      
      
          [HttpPost]
          [AllowAnonymous]
          [ValidateAntiForgeryToken]
          public async Task<ActionResult> Login(LoginModel details, string returnUrl)
          {
              if (ModelState.IsValid)
              {
                  AppUser user = await UserManager.FindAsync(details.Name, details.Password);
      
                  if (user == null)
                  {
                      ModelState.AddModelError("", "Invalid name or password.");
                  }
                  else
                  {
                      ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                      AuthManager.SignOut();
                      AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident);
      
                      user.LastLoginDate = DateTime.UtcNow;
                      await UserManager.UpdateAsync(user);
      
                      PrincipalExSerializeModel serializeModel = new PrincipalExSerializeModel();
                      serializeModel.UserExInfo = new UserExInfo()
                      {
                          BusinessInfo = await
                              db.Businesses
                              .Where(b => user.Id.Equals(b.AspNetUserID))
                              .Select(b => new UserExBusinessInfo { BusinessID = b.BusinessID, Name = b.Name })
                              .ToListAsync()
                      };
      
                      JavaScriptSerializer serializer = new JavaScriptSerializer();
      
                      string userData = serializer.Serialize(serializeModel);
      
                      FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                               1,
                               details.Name,
                               DateTime.Now,
                               DateTime.Now.AddMinutes(15),
                               false,
                               userData);
      
                      string encTicket = FormsAuthentication.Encrypt(authTicket);
                      HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                      Response.Cookies.Add(faCookie);
      
                      return RedirectToLocal(returnUrl);
                  }
              }
              return View(details);
          }
      

      最后在 Global.asax.cs 中

          protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
          {
              HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
      
              if (authCookie != null)
              {
                  FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                  JavaScriptSerializer serializer = new JavaScriptSerializer();
                  PrincipalExSerializeModel serializeModel = serializer.Deserialize<PrincipalExSerializeModel>(authTicket.UserData);
                  PrincipalEx newUser = new PrincipalEx(HttpContext.Current.User, serializeModel.UserExInfo);
                  HttpContext.Current.User = newUser;
              }
          }
      

      现在我可以通过调用来访问视图和控制器中的数据

      User.ExInfo()
      

      要退出,我只需调用

      AuthManager.SignOut();
      

      AuthManager 在哪里

      HttpContext.GetOwinContext().Authentication
      

      【讨论】:

        猜你喜欢
        • 2015-10-22
        • 2017-10-14
        • 2012-05-31
        • 2011-01-31
        • 2015-05-05
        • 2015-10-07
        • 2023-04-08
        • 2012-06-15
        相关资源
        最近更新 更多