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

I've read tons of articles and questions but I feel like I'm making it harder than it actually is. I thought it would be easy. If a user logs on, I want to set a custom IIdentity. So I thought, I will implement Application_PostAuthenticateRequest in my global.asax. However, that is called on every request, and I don't want to do a call to the database on every request which would request all the data from the database and put in a custom IPrincipal object. That also seems very unnecessary, slow, and in the wrong place (doing database calls there) but I could be wrong. Or where else would that data come from?

因此,我认为,每当用户登录时,我都可以在会话中添加一些必要的变量,这些变量将添加到Application_PostAuthenticateRequest事件处理程序中的自定义IIdentity中。然而,我的上下文。Session在那里是空的,所以这也不是正确的方法。

我已经为此工作了一天了,我觉得我遗漏了一些东西。这应该不难,对吧?我也对随之而来的所有(半)相关的东西感到困惑。MembershipProvider, MembershipUser, RoleProvider, ProfileProvider, IPrincipal, IIdentity, FormsAuthentication....难道只有我一个人对这一切感到困惑吗?

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


我不能直接代表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


下面是一个完成这项工作的例子。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);
     }
}

在全局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

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


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


我是这样做的。

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

Create the interface interface ICustomPrincipal : IPrincipal { int Id { get; set; } string FirstName { get; set; } string LastName { get; set; } } 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; } } CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object. public class CustomPrincipalSerializeModel { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } LogIn method - setting up a cookie with custom information 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 - Reading cookie and replacing HttpContext.User object, this is done by overriding 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; } } Access in Razor views @((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

作为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。角色、用户。Tasks, User.HasPath(int), User.Settings.Timeout和其他很多不错的东西)


如果您需要将一些方法连接到@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
            }
        }
    }

然后只需在区域网络中添加一个引用。配置,并在视图中像下面这样调用它。

@User.IsEditor()

在LukeP回答的基础上,结合Web.config,增加了设置超时和requireSSL的方法。

参考资料链接

MSDN,解释:表单认证在ASP。NET 2.0 MSDN, FormsAuthentication类 所以,.net Access Forms认证的“timeout”值在代码中

LukeP代码修改

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

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;

好吧,我在这里是一个严肃的密码管理员,通过拖动这个非常古老的问题,但有一个更简单的方法来解决这个问题,上面的@Baserz提到过。那就是使用c#扩展方法和缓存的组合(不要使用会话)。

事实上,Microsoft已经在Microsoft. aspnet . identity . identityextensions名称空间中提供了许多这样的扩展。例如,GetUserId()是一个返回用户Id的扩展方法。还有GetUserName()和FindFirstValue(),它们返回基于IPrincipal的声明。

因此,您只需要包含名称空间,然后调用User.Identity.GetUserName()来获得ASP配置的用户名。净的身份。

我不确定这是否被缓存,因为旧的ASP。NET Identity不是开源的,我也没有费心对它进行逆向工程。然而,如果不是,那么你可以编写自己的扩展方法,这将缓存这个结果的特定数量的时间。


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