ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

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

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

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

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

U
Undo

这是我的做法。

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

创建接口接口 ICustomPrincipal : IPrincipal { int Id { get;放; } 字符串名字 { 获取;放; } 字符串姓氏 { 获取;放; } } CustomPrincipal 公共类 CustomPrincipal : ICustomPrincipal { public IIdentity Identity { get;私人套装; } public bool IsInRole(string role) { return false; } public CustomPrincipal(string email) { this.Identity = new GenericIdentity(email); } 公共 int ID { 获取;放; } 公共字符串名字 { 获取;放; } 公共字符串姓氏 { 获取;放; } } CustomPrincipalSerializeModel - 用于将自定义信息序列化到 FormsAuthenticationTicket 对象中的 userdata 字段中。公共类 CustomPrincipalSerializeModel { public int Id { get;放; } 公共字符串名字 { 获取;放; } 公共字符串姓氏 { 获取;放; } } LogIn 方法 - 使用自定义信息设置 cookie if (Membership.ValidateUser(viewModel.Email, viewModel.Password)) { var user = userRepository.Users.Where(u => u.Email == viewModel.Email)。第一的(); CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();序列化模型.Id = 用户.Id; serializeModel.FirstName = user.FirstName; serializeModel.LastName = 用户.LastName; JavaScriptSerializer 序列化器 = new JavaScriptSerializer(); string userData = serializer.Serialize(serializeModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, viewModel.Email, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);字符串 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 序列化器 = new JavaScriptSerializer(); CustomPrincipalSerializeModel serializeModel = serializer.Deserialize(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.Id = 序列化模型.Id; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; HttpContext.Current.User = 新用户;在 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(); 对我来说很好。
C
Community

我不能直接说 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 数据。
M
Mrchief

这是完成工作的示例。 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 的实现。谷歌关于那个界面
R
Robert Westerlund

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


但是会话可能会丢失,用户仍然可以进行身份验证。不 ?
@brady gaster,我阅读了您的博文(谢谢!),为什么有人会使用您的帖子中提到的覆盖“OnAuthorize()”而不是另一个提到的 global.asax 条目“...AuthenticateRequest(..)”答案?在设置主要用户时,一个优先于另一个吗?
B
Base

如果您需要将一些方法连接到 @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 中。或者您实现自己的缓存逻辑。
C
Community

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

参考链接

MSDN,解释:ASP.NET 2.0 中的表单身份验证

MSDN,FormsAuthentication 类

SO,.net 访问表单身份验证“超时”值在代码中

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;

A
Alicia

作为 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 和许多其他好东西)


E
Erik Funkenbusch

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

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

因此,您只需包含命名空间,然后调用 User.Identity.GetUserName() 即可获取 ASP.NET Identity 配置的用户名。

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


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

我尝试了 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

S
Saeed Zhiany

/Web.config

<system.web> 下添加以下代码

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅