按照标准的ASP.NET Membership的做法,它不能提供这样的信息。Page.User.Identity.Name只是返回用户登录时使用的名称,在本例中是工号。
我们的目标是,能不能实现Page.User.Identity.Name显示用户的真实名称,而不是工号,甚至还可以显示其他的一些信息。
要实现这样的功能,我的思路是自定义身份验证。下面就是我的步骤,可以供大家参考
第一步:自定义IdentityIdentity在安全设计中很重要,他一般代表了用户标识。本例中,我们添加了几个特殊的属性
publicclass SECIdentity : IIdentity
{
publicstring DisplayName
{ get; set; }
publicstring Factory { get; set; }
publicstring Name { get; set; }
publicstring AuthenticationType { get { return "Custom Authentication"; } }
publicbool IsAuthenticated {
get { returntrue; } }
publicoverridestring ToString()
{ returnstring.Format("{0},{1}", Factory, DisplayName); }
}
第二步:自定义Principal
一个用户不仅需要有名称等基本信息,它还应该具有另外一些信息,例如角色等等。这可以通过封装成一个Principal来解决
publicclass SECPrincipal : IPrincipal
{ public SECPrincipal(string name, string displayName, string factory)
{ identity = new SECIdentity() { Name = name, DisplayName = displayName, Factory = factory };
}
private IIdentity identity;
public IIdentity Identity
{
get { return identity; }
}
publicbool IsInRole(string role)
{
returntrue; }
}
第三步:自定义MembershipProvider
我们需要有一个特殊的Provider,来读取自定义数据库,校验用户,并且把有关的数据都一起读出来,请注意,作为演示,我只是实现了这个Provider的一个方法:ValidateUser.其他的方法都没有实现
publicclass SECMembershipProvider:MembershipProvider{ publicoverridestring ApplicationName
{ get
{ thrownew NotImplementedException(); }
set
{ thrownew NotImplementedException();
}
}
publicoverridebool ChangePassword(string username, string oldPassword, string newPassword)
{
thrownew NotImplementedException();
}
publicoverridebool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
thrownew NotImplementedException();
}
publicoverride MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
thrownew NotImplementedException();
}
publicoverridebool DeleteUser(string username, bool deleteAllRelatedData)
{
thrownew NotImplementedException();
}
publicoverridebool EnablePasswordReset
{
get { thrownew NotImplementedException(); }
}
publicoverridebool EnablePasswordRetrieval
{
get { thrownew NotImplementedException(); }
}
publicoverride MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, outint totalRecords)
{
thrownew NotImplementedException();
}
publicoverride MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, outint totalRecords)
{
thrownew NotImplementedException();
}
publicoverride MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, outint totalRecords)
{
thrownew NotImplementedException();
}
publicoverrideint GetNumberOfUsersOnline()
{
thrownew NotImplementedException();
}
publicoverridestring GetPassword(string username, string answer)
{
thrownew NotImplementedException();
}
publicoverride MembershipUser GetUser(string username, bool userIsOnline)
{
thrownew NotImplementedException();
}
publicoverride MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
thrownew NotImplementedException();
}
publicoverridestring GetUserNameByEmail(string email) {
thrownew NotImplementedException();
}
publicoverrideint MaxInvalidPasswordAttempts {
get { thrownew NotImplementedException(); }
}
publicoverrideint MinRequiredNonAlphanumericCharacters {
get { thrownew NotImplementedException(); }
}
publicoverrideint MinRequiredPasswordLength {
get { thrownew NotImplementedException(); }
}
publicoverrideint PasswordAttemptWindow {
get { thrownew NotImplementedException(); }
}
publicoverride MembershipPasswordFormat PasswordFormat {
get { thrownew NotImplementedException(); }
}
publicoverridestring PasswordStrengthRegularExpression {
get { thrownew NotImplementedException(); }
}
publicoverridebool RequiresQuestionAndAnswer {
get { thrownew NotImplementedException(); }
}
publicoverridebool RequiresUniqueEmail
{ get { thrownew NotImplementedException(); }
}
publicoverridestring ResetPassword(string username, string answer)
{
thrownew NotImplementedException();
}
publicoverridebool UnlockUser(string userName)
{
thrownew NotImplementedException(); }
publicoverridevoid UpdateUser(MembershipUser user)
{
thrownew NotImplementedException();
}
publicoverridebool ValidateUser(string username, string password)
{//这里可以实际读取数据库,对用户名和密码进行校验
if (username == "007" && password == "password") { var cookie = new HttpCookie(username + "_data");
cookie.Values.Add("displayName", "ares");
cookie.Values.Add("factory", "shanghai");
HttpContext.Current.Response.Cookies.Add(cookie); returntrue;
}
returnfalse; }
}
大家注意这个ValidateUser方法,我们除了校验用户之外,还可以将用户的displayName和factory读取出来,放在cookie里面。这是为了下一步做准备。
第四步:注册使用这个MembershipProvider<membershipdefaultProvider="SECMembershipProvider"><providers><clear/><addname="SECMembershipProvider"type="MvcApplicationSample.Extensions.SECMembershipProvider,MvcApplicationSample"/><addname="AspNetSqlMembershipProvider"type="System.Web.Security.SqlMembershipProvider"connectionStringName="ApplicationServices"enablePasswordRetrieval="false"enablePasswordReset="true"requiresQuestionAndAnswer="false"requiresUniqueEmail="false"maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6"minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10"applicationName="/"/></providers></membership>第五步:修改HttpContext.User属性
这是我们至关重要的一步。我们希望替换掉默认那个HttpContext.User。
请注意,这个操作必须在一个特殊事件中来完成。请转到global.asax文件中,添加如下代码
void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender; if (app.User.Identity.IsAuthenticated)
{
var userName = app.User.Identity.Name;
var cookie = app.Request.Cookies[userName + "_data"];
var displayName = cookie.Values["displayName"];
var factory = cookie.Values["factory"];
HttpContext.Current.User= new Extensions.SECPrincipal(userName, displayName, factory);
}
}
第六步:使用自定义的Principal
我们在页面中,就可以很容易地使用自定义的这个Principal了。
Welcome <b><%: Page.User.Identity.ToString() %>
下面是一个最后的结果。这个项目是最近做给客户做MVC理论和实践课程中的一个范例。仅供参考