gpt4 book ai didi

asp.net-mvc - 如何在 ASP.NET MVC 中为自定义用户对象实现标识?

转载 作者:行者123 更新时间:2023-12-05 00:33:32 25 4
gpt4 key购买 nike

在我的 ASP.NET MVC 应用程序中,我试图创建一个自定义的 HttpContent.User 对象。我首先创建了一个实现 IPrincioal 的 Member 类。

public class Member : IPrincipal
{
public string Id { get; set; }
public IIdentity Identity { get; set; }
public bool IsInRole(string role) { throw new NotImplementedException(); }
...
}

然后在身份验证时,我将 HttpContext.User 设置为 Member 类的实例:
FormsAuthentication.SetAuthCookie(email, false);
HttpContext.User = member;

然后我想检查用户是否通过身份验证,如下所示:
if (User.Identity.IsAuthenticated) { ... }

这就是我被困的地方。 我不确定我需要为 public IIdentity Identity 做什么成员实例上的属性。 这样我就可以像这样使用 HttpContext.User 对象:
IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
ViewBag.IsAuthenticated = IsAuthenticated;

if (IsAuthenticated) {
CurrentMember = (Member)HttpContext.User;
ViewBag.CurrentMember = CurrentMember;
}

最佳答案

Principal 不是您可以在编写 auth cookie 时设置一次然后忘记的东西。在后续请求期间,将读取 auth cookie 并且 IPrincipal/IIdentity在执行操作方法之前重建。发生这种情况时,尝试转换 HttpContext.User到您的定制 Member type 会抛出异常。

一种选择是拦截 ActionFilter ,然后包装标准实现。

public class UsesCustomPrincipalAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var systemPrincipal = filterContext.HttpContext.User;
var customPrincipal = new Member(systemPrincipal)
{
Id = "not sure where this comes from",
};
filterContext.HttpContext.User = customPrincipal;
}
}

public class Member : IPrincipal
{
private readonly IPrincipal _systemPrincipal;

public Member(IPrincipal principal)
{
if (principal == null) throw new ArgumentNullException("principal");
_systemPrincipal = principal;
}

public string Id { get; set; }

public IIdentity Identity { get { return _systemPrincipal.Identity; } }

public bool IsInRole(string role)
{
return _systemPrincipal.IsInRole(role);
}
}

这样,您就不会丢失任何使用默认值 IPrincipal 开箱即用的内容。和 IIdentity实现。您仍然可以调用 IsAuthenticatedIIdentity ,甚至 IsInRole(string)IPrincipal .您唯一获得的是额外的 Id您的自定义属性 IPrincipal实现(尽管我不确定它来自哪里或为什么需要它)。

关于asp.net-mvc - 如何在 ASP.NET MVC 中为自定义用户对象实现标识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11912125/

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