按照標(biāo)準(zhǔn)的ASP.NET Membership的做法,它不能提供這樣的信息。Page.User.Identity.Name只是返回用戶登錄時(shí)使用的名稱,在本例中是工號(hào)。
我們的目標(biāo)是,能不能實(shí)現(xiàn)Page.User.Identity.Name顯示用戶的真實(shí)名稱,而不是工號(hào),甚至還可以顯示其他的一些信息。
要實(shí)現(xiàn)這樣的功能,我的思路是自定義身份驗(yàn)證。下面就是我的步驟,可以供大家參考
第一步:自定義IdentityIdentity在安全設(shè)計(jì)中很重要,他一般代表了用戶標(biāo)識(shí)。本例中,我們添加了幾個(gè)特殊的屬性
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
一個(gè)用戶不僅需要有名稱等基本信息,它還應(yīng)該具有另外一些信息,例如角色等等。這可以通過封裝成一個(gè)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
我們需要有一個(gè)特殊的Provider,來讀取自定義數(shù)據(jù)庫(kù),校驗(yàn)用戶,并且把有關(guān)的數(shù)據(jù)都一起讀出來,請(qǐng)注意,作為演示,我只是實(shí)現(xiàn)了這個(gè)Provider的一個(gè)方法:ValidateUser.其他的方法都沒有實(shí)現(xiàn)
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)
{//這里可以實(shí)際讀取數(shù)據(jù)庫(kù),對(duì)用戶名和密碼進(jìn)行校驗(yàn)
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; }
}
大家注意這個(gè)ValidateUser方法,我們除了校驗(yàn)用戶之外,還可以將用戶的displayName和factory讀取出來,放在cookie里面。這是為了下一步做準(zhǔn)備。
第四步:注冊(cè)使用這個(gè)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屬性
這是我們至關(guān)重要的一步。我們希望替換掉默認(rèn)那個(gè)HttpContext.User。
請(qǐng)注意,這個(gè)操作必須在一個(gè)特殊事件中來完成。請(qǐng)轉(zhuǎn)到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
我們?cè)陧?yè)面中,就可以很容易地使用自定義的這個(gè)Principal了。
Welcome <b><%: Page.User.Identity.ToString() %>
下面是一個(gè)最后的結(jié)果。這個(gè)項(xiàng)目是最近做給客戶做MVC理論和實(shí)踐課程中的一個(gè)范例。僅供參考