Adding OpenID to your web site in conjunction with ASP.NET Membership
2010-09-10 14:07
453 查看
Irecentlyaddedmembership,accounts,login,etc.tothe
1.DownloadtheawesomeC#OpenIDlibrary,
2.AddsomeniceusabilityfeaturestoyourOpenIDlogin.Goto
DidImentionthatthisissoeasythatIdon'tknowwhyeveryoneisn'tsupportingOpenID?GoingforwardIwillbedoingsoineverynewsitethatIcreateandI'llretrofitexistingsiteswhenIgetthechance.
3.Readthefollowingarticles:
AfterreadingtheaboveyouwillhaveaprettygoodunderstandingofhowtoaddOpenIDtoyoursite.Someofthecodeexamplesintheearlier3postsbyAndrewarealittleoutofdate.AsofthewritingofthispostthecodeprovidedinHanselman'sblogpostarethemostuptodate.Goaheadandreadthetwo"MVC"postsbyAndrewevenifyouarenotinterestedinASP.NETMVC.Theconceptsdisplayedinthosepostscanbeusedanywhere.Infact,itwasinofthosepostswhereIfoundmyinspirationforovercomingmynexthurdle.
TheonlythingthatwasmissingformewasintegrationwithASP.NETmembership.Iactuallyfoundverylittleinformationforaccomplishingthis.Ifoundquitealotofquestionsaskinghowtodoit,butmostoftheanswerswerejustmorequestionsaskingwhyyouwouldwanttodoit.
4.Createyourloginform(orusercontrolorcompositeservercontrolorwhateveryouprefer).InmycaseIcreatedausercontrolthatholdsjustthefieldsnecessaryforOpenIDloginandthelogicbehindthem.Doingsoallowsmetodropthatcontrolintoanyexistingloginpage(showninimageabove)ormyexistingcreateaccountpageoranywhereelseIwanttouseit.MakesureyouaddthejavascriptfortheIDSelector.
ForallowingtraditionalASP.NETmembershiploginanduseraccountcreationIjustdroppedthebasicoutoftheboxcontrolsonthepage.
5.Wireuptheloginsubmitbutton.Ididsomethinglikebelow,whichisverysimilartoexamplesthatAndrewandScottHanselmanprovided.BasicallyI'mjusttellingtheOpenIDproviderthatIneedtheuser'semailandnickname(foruseinthenextstep):
protectedvoidloginButton_Click(objectsender,EventArgse){
if(!openidValidator.IsValid)return;//don'tloginifcustomvalidationfailed.
OpenIdRelyingPartyopenid=newOpenIdRelyingParty();
try{
IAuthenticationRequestrequest=openid.CreateRequest(openid_identifier.Text);
ClaimsRequestfetch=newClaimsRequest();
fetch.Nickname=DemandLevel.Require;
fetch.Email=DemandLevel.Require;
request.AddExtension(fetch);
request.RedirectToProvider();
}catch(OpenIdExceptionex){
//TheuserprobablyenteredanIdentifierthat
//wasnotavalidOpenIDendpoint.
openidValidator.Text=ex.Message;
openidValidator.IsValid=false;
}
}
6.HandletheresponsefromtheOpenIDprovider.ThissnippetofcodeispartoftheloginprocessandexpandsuponexamplesfromAndrewArnott'sandScottHanselman'spostslinkedtopreviously.
HereI'mpullingthealiasandemailaddressthatIrequestedinthepreviousstep.WiththatinformationIchecktoseeiftheuseralreadyexistsintheASP.NETmembershipdatastore.IfnotIwillcreateaMembershipaccountforthemusingtheirOpenIDURIastheirusername.WhenIcreatetheaccountyoucanseethatI'mgeneratingarandomstringfortheuser'spasswordfieldandpasswordanswerfield.You'llalsoseethatI'madding"ThisisanOpenIDaccount.YoushouldloginwithyourOpenID."asthepasswordquestion.ThatwayifauserforgetstheyusedOpenIDandtriestologinthroughthetraditionalusername/passwordloginformandselectsthattheyforgottheirpasswordwhenthelogindoesn'twork,heorshewillgetareminderabouttheirOpenIDintheformofthepasswordquestion.Iknowit'sahack,butitworksfornowformymodestneedsandI'mhappywithit.
Nextyou'llseethatafterIcreatetheMembershipUserIthensettheuser's"comment"fieldtotheirNickname.Thisisbecausethe"Hello,Username.Welcomebacktothesite."messageatthetopofthepagewouldnormallydisplaytheuser's"username".InthecaseofOpenIDuserstheirusernamewouldbetheirOpenIDURI-somethinglike:
Finally,IjustcallFormsAuthentication.RedirectFromLoginPage()passingintheirOpenIDURIthattheyprovided,loggingthemintothesite.
caseAuthenticationStatus.Authenticated:
ClaimsResponsefetch=openid.Response.GetExtension(typeof(ClaimsResponse))asClaimsResponse;
stringalias=fetch.Nickname;
stringemail=fetch.Email;
if(string.IsNullOrEmpty(alias))
alias=openid.Response.ClaimedIdentifier;
if(string.IsNullOrEmpty(email))
email=openid.Response.ClaimedIdentifier;
//Nowseeiftheuseralreadyexists,ifnotcreatethem
if(Membership.GetUser(openid.Response.ClaimedIdentifier)==null)
{
MembershipCreateStatusmembershipCreateStatus;
MembershipUseruser=Membership.CreateUser(openid.Response.ClaimedIdentifier,
Common.GetRandomString(5,7),
email,
"ThisisanOpenIDaccount.YoushouldloginwithyourOpenID.",
Common.GetRandomString(5,7),
true,
outmembershipCreateStatus);
if(membershipCreateStatus!=MembershipCreateStatus.Success)
{
loginFailedLabel.Text+=":UnsuccessfulcreationofAccount:"+membershipCreateStatus.ToString();
loginFailedLabel.Visible=true;
break;
}
user.Comment=alias;
Membership.UpdateUser(user);
}
//UseFormsAuthenticationtotellASP.NETthattheuserisnowloggedin,
//withtheOpenIDClaimedIdentifierastheirusername.
FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier,chkRememberMe.Checked);
break;
That'sallthereistoit.Nowyoucanallowyouruser'stochoosewhetherthey'dliketocreateanaccountonyoursitebycreatinganewusernameandpasswordorbyusingtheirneworexistingOpenID.ThebonuswiththismethodisthatitallowsyoutoaddOpenIDsupporttoanexistingsitethatalreadyhastraditionalmembershipwithoutbreakinganything.
Enjoyandletmeknowifyouhaveanyquestionsorcomments.
相关文章推荐
- How to generate an RSS feed for your web site using ASP.NET
- How to use AspnetUpload™ in your web application
- ASP.NET 4.5.256 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5.256 in order for your site to run correctly
- How to generate an RSS feed for your web site using ASP.NET
- 海洋工作室——网站建设专家:ASP.NET: How to Convert Your Site To A MasterPage Site in 3 Steps
- How to take screenshot (thumbnail) of a web site with ASP.NET 2.0?
- Speed Up Your Site with the Improved View State in ASP.NET 2.0
- The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the ser
- Adding dynamic nodes to ASP.NET site maps at runtime by deriving from StaticSiteMapProvider
- Many ways to communicate with your database using jQuery AJAX and ASP.NET
- Adding the Test API in The ASP.NET Web API Help Page
- Test your ASP.NET MVC or WebForms Application on IIS 7 in 30 seconds
- Adding dynamic nodes to ASP.NET site maps at runtime by deriving from StaticSiteMapProvider
- How to add icons to a SiteMap Menu in ASP .NET
- How To: Prevent Cross-Site Scripting in ASP.NET
- Generate Kindle (MOBI) ebooks with your ASP.NET Web API
- Working with Web Resources in ASP.NET 2.0
- How to call webservices with ASP.NET at Run time?
- HOW TO: Upload a File to a Web Server in ASP.NET by Using Visual Basic .NET
- How to integrate custom security policy with Windows domain authentication in ASP.NET