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上有类似的问题,但如果我需要的答案就在那里,我一定会忽略。


#1楼

这是我如何做到的。

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

  1. 创建界面

     interface ICustomPrincipal : IPrincipal { int Id { get; set; } string FirstName { get; set; } string LastName { get; set; } } 
  2. CustomPrincipal

     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

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

此外,为了使访问更加容易,您可以创建一个基本控制器并覆盖返回的User对象(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

#2楼

我不能直接代表ASP.NET MVC,但对于ASP.NET Web Forms,诀窍是创建一个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


#3楼

如果您希望简化页面后面代码中的访问,那么作为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和许多其他好东西)


#4楼

如果您需要将某些方法连接到@User以在视图中使用,这是一个解决方案。 对于任何严肃的会员制定制都没有解决方案,但如果单独的观点需要原始问题那么这也许就足够了。 下面用于检查从authorizefilter返回的变量,用于验证是否有某些链接无法呈现(不适用于任何类型的授权逻辑或访问授权)。

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()

#5楼

基于LukeP的答案 ,并添加一些方法来设置timeoutrequireSSLWeb.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;

#6楼

这是完成工作的一个例子。 通过查看一些数据存储(假设您的用户数据库)来设置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);
     }
}

在golbal 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

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


#7楼

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

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

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

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


#8楼

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

#9楼

MVC为您提供了从控制器类中挂起的OnAuthorize方法。 或者,您可以使用自定义操作筛选器来执行授权。 MVC让它变得非常简单。 我在这里发布了一篇关于此的博文。 http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值