我需要做一些相当简单的事情:在我的 ASP.NET MVC 应用程序中,我想设置一个自定义的 IIdentity / IPrincipal。哪个更容易/更合适。我想扩展默认值,以便可以调用 User.Identity.Id
和 User.Identity.Role
之类的东西。没什么特别的,只是一些额外的属性。
我已经阅读了大量的文章和问题,但我觉得我让它变得比实际更难。我以为这很容易。如果用户登录,我想设置自定义 IIdentity。所以我想,我将在我的 global.asax 中实现 Application_PostAuthenticateRequest
。但是,在每个请求上都会调用它,并且我不想在每个请求上都调用数据库,因为它会从数据库中请求所有数据并放入自定义 IPrincipal 对象。这似乎也非常不必要,很慢,而且在错误的地方(在那里进行数据库调用),但我可能是错的。或者这些数据还来自哪里?
所以我想,每当用户登录时,我都可以在我的会话中添加一些必要的变量,我将这些变量添加到 Application_PostAuthenticateRequest
事件处理程序中的自定义 IIdentity 中。但是,我的 Context.Session
在那里 null
,所以这也不是要走的路。
我已经为此工作了一天,我觉得我错过了一些东西。这应该不难做到,对吧?我也对随之而来的所有(半)相关内容感到有些困惑。 MembershipProvider
、MembershipUser
、RoleProvider
、ProfileProvider
、IPrincipal
、IIdentity
、FormsAuthentication
.... 是不是只有我一个人觉得这一切都很混乱?
如果有人能告诉我一个简单、优雅、高效的解决方案,可以在 IIdentity 上存储一些额外的数据,而不需要额外的模糊......那就太好了!我知道关于 SO 有类似的问题,但如果我需要的答案在那里,我一定忽略了。
MemberShip...
、Principal
、Identity
。 ASP.NET 应该使这更容易、更简单,并且最多有两种处理身份验证的方法。
这是我的做法。
我决定使用 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
在代码中:
(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
我不能直接说 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
Cache
作为 Session
的替代品,以将数据保留在服务器上。谁能告诉我这是否是一种有缺陷的方法?
这是完成工作的示例。 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
这将允许您访问自定义用户信息。
MVC 为您提供了挂在控制器类上的 OnAuthorize 方法。或者,您可以使用自定义操作过滤器来执行授权。 MVC 使它很容易做到。我在这里发布了一篇关于此的博客文章。 http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0
如果您需要将一些方法连接到 @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()
在 LukeP's answer 的基础上,增加了一些方法来设置 timeout
和 requireSSL
与 Web.config
配合。
参考链接
MSDN,解释:ASP.NET 2.0 中的表单身份验证
MSDN,FormsAuthentication 类
SO,.net 访问表单身份验证“超时”值在代码中
LukeP的修改代码
1、根据Web.Config
设置timeout
。 FormsAuthentication.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;
作为 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.Roles
、User.Tasks
、User.HasPath(int)
、User.Settings.Timeout
和许多其他好东西)
好的,所以我在这里是一个严肃的密码管理员,提出了这个非常古老的问题,但是有一个更简单的方法,上面的@Baserz 提到了这一点。那就是使用 C# 扩展方法和缓存的组合(不要使用会话)。
事实上,Microsoft 已经在 Microsoft.AspNet.Identity.IdentityExtensions
命名空间中提供了许多此类扩展。例如,GetUserId()
是返回用户 ID 的扩展方法。还有 GetUserName()
和 FindFirstValue()
,它们根据 IPrincipal 返回声明。
因此,您只需包含命名空间,然后调用 User.Identity.GetUserName()
即可获取 ASP.NET Identity 配置的用户名。
我不确定这是否被缓存,因为旧的 ASP.NET 标识不是开源的,我也没有费心对其进行逆向工程。但是,如果不是,那么您可以编写自己的扩展方法,它将将此结果缓存特定的时间。
IsUserAdministrator
或 UserEmail
等信息?你在想HttpRuntime.Cache
吗?
我尝试了 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
/Web.config
:
在 <system.web>
下添加以下代码
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
不定期副业成功案例分享
Thread.CurrentPrincipal
设置为Application_PostAuthenticateRequest
才能使其工作,因为它不依赖于HttpContext.Current.User
FormsAuthentication.SignOut();
对我来说很好。