gpt4 book ai didi

ASP.NET MVC - 设置自定义 IIdentity 或 IPrincipal

转载 作者:行者123 更新时间:2023-12-01 15:05:54 25 4
gpt4 key购买 nike

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

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

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

我已经为此工作了一天,我觉得我错过了一些东西。这应该不难做到,对吧?我也对随之而来的所有(半)相关内容感到有些困惑。 MembershipProvider , MembershipUser , RoleProvider , ProfileProvider , IPrincipal , IIdentity , FormsAuthentication ....我是唯一一个觉得这一切都非常困惑的人吗?

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

最佳答案

这是我的做法。

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

  • 创建接口(interface)
    interface ICustomPrincipal : IPrincipal
    {
    int Id { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
    }
  • 自定义主体
    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; }
    }
  • CustomPrincipalSerializeModel - 用于将自定义信息序列化到 FormsAuthenticationTicket 对象中的 userdata 字段中。
    public class CustomPrincipalSerializeModel
    {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    }
  • 登录方法 - 使用自定义信息设置 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");
    }
  • 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;
    }
    }
  • 在 Razor View 中访问
    @((User as CustomPrincipal).Id)
    @((User as CustomPrincipal).FirstName)
    @((User as CustomPrincipal).LastName)

  • 在代码中:
        (User as CustomPrincipal).Id
    (User as CustomPrincipal).FirstName
    (User as CustomPrincipal).LastName

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

    此外,为了使访问更容易,您可以创建一个基本 Controller 并覆盖返回的用户对象 (HttpContext.User):
    public class BaseController : Controller
    {
    protected virtual new CustomPrincipal User
    {
    get { return HttpContext.User as CustomPrincipal; }
    }
    }

    然后,对于每个 Controller :
    public class AccountController : BaseController
    {
    // ...
    }

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

    但这在 View 内部不起作用。为此,您需要创建一个自定义 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>

    在 View 中,您可以像这样访问它:
    @User.FirstName
    @User.LastName

    关于ASP.NET MVC - 设置自定义 IIdentity 或 IPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1064271/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com