您的位置:首页 > 编程语言 > ASP

Adding OpenID to your web site in conjunction with ASP.NET Membership

2010-09-10 14:07 453 查看

Irecentlyaddedmembership,accounts,login,etc.totheAspDotNetMVCsite.WhiledoingsoIdecidedIwantedtosupportOpenID,too.However,Ididn'twanttogowithonlyOpenIDbecauseIneededASP.NETMembershipinplacetoworkinconjunctionwithanotherapplication,aKiggsiteusedasaserviceforratingcontentontheAspDotNetMVCsite.IcouldhaveprobablyconvertedtheKiggcodebasetouseOpenIDbutIalsowantedtoallowpeoplewhomaynothaveOpenIDtocreatetraditionalaccountsonthesitewithoutsigningupforOpenID.FollowingarethestepsItooktoimplementanOpenIDloginandintegrateitwith"traditionalASP.NET"membership.Followthesesixstepsandyoucandothesame.

1.DownloadtheawesomeC#OpenIDlibrary,DotNetOpenIdfromGoogleCode,andadditasareferenceinyourproject.ThisisagreatopensourcelibrarydevelopedbyAndrewArnott,JasonAlexander,ScottWatermasysk,ScottHanselman,JoeBrinkmanandothers.Itseriouslydoesalltheheavylifting,comeswithsomegoodexamples,andAndrewArnottisdoingagreatjobofmakingpostsaboutfringecasesonhisblog.

2.AddsomeniceusabilityfeaturestoyourOpenIDlogin.GotoIDSelector,createanaccountandgrabthecoupleoflinesofJavaScripttocreatethecoolOpenIDserviceselectorshownintheimageatright.

DidImentionthatthisissoeasythatIdon'tknowwhyeveryoneisn'tsupportingOpenID?GoingforwardIwillbedoingsoineverynewsitethatIcreateandI'llretrofitexistingsiteswhenIgetthechance.


3.Readthefollowingarticles:

HowtoaddOpenIDtoyourASP.NETwebsite(inC#orVB.NET)-AndrewArnott

AddOpenIDloginsupporttoyourASP.NETMVCsite-AndrewArnott

EnhancingtheASP.NETMVCOpenIDloginexperience-AndrewArnott

HowtoaddOpenIDtoyourASP.NETformswebsitewithoutusingASP.NETControls-AndrewArnott

HowtouseDotNetOpenId'sAttributeExchangeextension-AndrewArnott

TheWeeklySourceCode#35-OpenIDEdition-ScottHanselman

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:http://danhounshell.openidprovidername.com/.That'sabituglyandI'dratherusetheNicknamethatIaskedfromthenwhentheyloggedinwithOpenID.ByshovingtheNicknameintothecommentsfieldIcanfirstchecktoseeifithasavalueandifsouseitinthedisplayratherthantheirusername.Ifitdoesn'thaveavaluethenIcandefaulttotheusername.Sonowusingmypreviousexampleitwillsay"Hello,DanHounshell.Welcomebacktothesite."Thissamethingcouldbeaccomplishedinacoupleofotherways.Throwingthenicknameintothesessionobjectorputtingitinacookieareotherreasonablealternatives.InmycaseIdon'tusethecommentsfieldforanythingelsesoonceagain-Iknowit'sahack,butitworksfornowformymodestneedsandI'mhappywithit.Plusit'seasytogettobyjustwriting"user.Comment".Thinkingaboutit,itmightbenicetowriteanextensionmethodforMembershipUsercalledDisplayNamethatdetermineswhethertousetheuser.Commentpropertyortheuser.Usernameproperty.

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐