Escolar Documentos
Profissional Documentos
Cultura Documentos
Oracle&ApexGeekery:RememberMeAPEXAutologin
Oracle&ApexGeekery
Andanotherthing...
Friday,October12,2012
AboutMe
ChristianRokitta
Follow
144
Viewmycomplete
profile
RememberMeAPEXAutologin
IpromisedtopublishaboutthissubjecttooneoftheattendeesduringmypresentationatKScope12inSanAntonio.Iusedthisfunctionalityin
mydemoapplication(FifApex)anditseemsthereisinterestinhowtodothis.
Most of the public websites like Facebook, LinkedIn, Twitter, Amazon or OTN do have it: an option to stay logged in, even if you closed the
browser,soyoudonothavetoauthenticateeachtimeyouvisitthesiteagain.Imprettyusedtoitandwouldbesurprisedifawebsitedidntoffe
thisconvenientfeature.OK,itsnotentirelysecure,but,asIsaid,veryconvenient.
Imworkingonaconsumersite/application,ImbuildingitwithAPEXandIwanttoofferthisremembermeoptiontoo.IknewanAPEXbased
website that does offer this feature (www.plsqlchallenge.com) and I had a chat with the developer that implemented its login mechanism,
BroughtonfromApexEvangelists.So,heremythankstohimfortheoriginalinspiration.
Oracle Application Express has neither a build in functionality nor is it providing a standard Authentication Schema that does provide this
mechanism.But,withjustalittleeffortyoucanimplementthisAutologininyourapplication.MyexampleusesaCustomAuthenticationschema
meaningIhaveausertableandapackage,providingallthenecessaryfunctionality.Atthebottomofthispost,youwillfindlinks,whereyoucan
downloadallfilesyouneedtoinstallthedemoapplicationinyourownenvironment.
Pages
Home
Letsstart
MyEventAgenda
DemoAPEXApplication
themes4apex
APEX.nlYouronestopOracle
APEXNews&Blogsite
AndAnotherThing...
Thestormhadnowdefinitely
abated,andwhatthunderthere
wasnowgrumbledovermore
distanthills,likeamansaying"And
anotherthing"twentyminutes
afteradmittinghe'slostthe
argument.
Firstofall,letmedefinethemechanism:theusergetsanoption,usuallyacheckbox,inloginscreen
tostaysignedin.Nexttimetheusevisitsthesite,hedoesnthavetoprovidehiscredentialsandis
automagicallysignedin.
The common technique to achieve this, is using a cookie that holds a token to identify the returning
user. So we have to set a cookie when the user signs into the application and check for the cookie
andvalidatethetokenwhentheusercomesback.
Settingandreadingacookieiseasy,usingtheOWA_COOKIEpackage,buthowtointegratethisinto
aAPEXauthenticationschema?
ThefollowingexampleisbuildwithastandardemptyapplicationwithCustomAuthentication.PriorI
createdatabletoholdtheuserdataandapackage,containingtheauthenticationlogic.Note:thisis
asimplifiedexample,sousingthisinyourproductionapplicationisatyourownrisk!Allcode
isincludedinthedemoapplicationdownload.
CREATETABLEmy_custom_users(
usernameVARCHAR2(25BYTE)
,passwordVARCHAR2(250BYTE)
,tokenVARCHAR2(25BYTE)
)
INSERTINTOmy_custom_users(username,password,token)
VALUES('DEMO',my_cust_auth.encodeit('DEMO','demo'),NULL)
COMMIT
Step1:settingthecookieduringlogin
APEXSmartPivotPlugin
FirstImgoingtomodifythegeneratedLoginPage(101),addingtheRemembermecheckbox.
Then I modify the Set Username Cookie process that already should exists and stores the APEX
usernameinacookie(Idonotmakeanychangestothisfunctionality):ThecodeIadd,checks,ifthe
Remembermehasbeentickedbytheuser,theuseractuallyisavaliduserfrommytableandthen
sets a cookie, called REMEMBER_ME. The value of this cookie is generated by a function,
producingarandomstringandstoringthisasatokenwiththeuserdataorfetchesthetokenfromthe
userdata,ifalreadyexisting.Inmyexample,Ichoosetosettheexpirationdateofthiscookieoneto
aboutayear.
TheSmartPivotPluginenables
userstocreatemultidimensional
pivotreportsusingdraganddrop
functionality.Easilyconfiguresub
andgrandtotalsjustlikeinExcel,in
anyAPEXapplication.
BlogArchive
2014(2)
2013(8)
2012(11)
December(1)
November(2)
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
1/7
9/13/2015
Oracle&ApexGeekery:RememberMeAPEXAutologin
October(1)
RememberMeAPEX
Autologin
September(1)
August(2)
June(1)
April(1)
March(2)
2011(2)
2010(7)
2009(6)
Books
OurBook:
OracleApplication
Express...
0,00
byRoelHartman,ChristianRokitta
andDavidPeake
BooksIdidread
(orshouldhaveread):
OracleApplication
Express...
Running the application, logging in with the checkbox ticked, you can exam the cookies of your APEX application by using a tool like the
DeveloperConsoleofChrome.Nexttosomecookies,setbyAPEXitself,youshouldfindtheREMEMBER_MEentryholdingthetokenstring
andexpiredateoftoday+365days:
ProOracle
ApplicationExpr...
BeginningOracle
Applicatio...
OracleApplication
Express...
OraclePl/SqlBest
Practice...
Step2:usingthecookieonreturn
OraclePL/SQL
Programming
MyPL/SQLChallengeProfile
ODTUGAPEXCommunity
OracleApplicationExpress
OracleTechnologyNetwork
SubscribeTo
Now,whendoweneedtoreadtheREMEMBER_MEcookieagain?Everytimethevisitorreturnstoyoursite/application,hasnotsignedinye
(obviously,aswewanttodothisautomagically)andthecookieissetandholdsatokenthatisknownintheusertable(assumingthattheuseris
thesameagain!). I want to perform the check, regardless of the page visited is a public page or a page that requires authentication. The even
thatshouldbetriggered,iftheconditionsaremet(cookiesetandvalid,userispublic), is the a automatic login, similar to the original login. To
performthecheck,IwillusePAGE0,butletsfirstcreatetheautologinfunctionalitytobecalled:
To realize the autologin, I create a new page (103 in example application). This page only
contains a On Load Before Header process and one page item. The process only fires
when the request name is AUTOLOGIN and calls the build in standard APEX login
procedure provided for custom authentication. It uses the page item to P103_TOPAGE as
targetpageaftersuccessfullogin,whichIwillsetonthetriggeringprocess/branchonpage0
to return to the page the user actually requested in the URL. The username is derived from
the cookie (the token belonging to one unique user) using the call OWA_COOKIE.ge
('REMEMBER_ME')inastoredprocedure.
wwv_flow_custom_auth_std.login(
P_UNAME=>my_cust_auth.get_user_from_cookie,
P_PASSWORD=>null,
P_SESSION_ID=>v('APP_SESSION'),
P_FLOW_PAGE=>:APP_ID||':'||:P103_TOPAGE
)
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
2/7
9/13/2015
Oracle&ApexGeekery:RememberMeAPEXAutologin
Posts
As you see, the password parameter is NULL. So I have to add logic to the Authentication
Function (my_cust_auth.validate_user) of my custom Authentication Schema, that handles
two cases: either a valid combination of username/password is given, or the
REMEMBER_ME token is set and a corresponding user is found. Again: this is very basic
andmaynotbesufficientforyourproductionapplication.
Comments
Followers
Step3:automagicallydoit
Jointhissite
IalreadymentionedthatIwillusePage0tocalltheautologin.Doingso,theusershouldbe
singed into the application, regardless which page he opens first. I simply create a Afte
HeaderRegionoftypeDynamicPL/SQL.TheredirectwillbedoneusingtheAPEXbuildin
procedure sys.owa_util.redirect_url, passing the relative URL of page 103 with reques
parameterAUTOLOGIN.Thisregionisconditional,checkingfor:userispublic,cookieisse
andbelongstoauser.
withGoogleFriendConnect
Members(30) More
Alreadyamember?Signin
I added an extra condition checking for the current page ID to be less or equal to 101, to prevent page 103 from recursively calling itself. Page
102willbethisdemoapplicationsspeciallogoutpage(seenextsection).AllnormalpagesinthisapplicationareassumedtohaveIDsinthe
rageof1to100.YoudefinitelyshouldmodifythisconditiontomeetyouractualapplicationspageIDranges.
Notetomyself:IfirsttriedtouseaBeforeHeaderBranchinPage0toimplementthisredirect.But:BranchesinPage0donot
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
3/7
9/13/2015
Oracle&ApexGeekery:RememberMeAPEXAutologin
evergetexecuted.ItsnotthefirsttimeIhitthispitfall.Afterall:theAPEX4.1ApplicationBuilderTreeview
ofPage0suggestsBranchesarepossible.
Step4:forgetme
We need to offer the user a way to logout and remove the cookie. I create a new page, 102, containing one On
LoadBeforeHeaderprocessandabranch.
Theprocessremoves(expiresandreplacesvaluewithemptystring)thecookieandperformstheactuallogout
usingWW_FLOW_CUSTOM_AUTH_STD.LOGOUT.Thebranchwilltaketheusertothe(public)Homepage
(1).
Ithenspecifytousepage102astheLogoutURLofmyAuthenticationSchema.
The request name LOGOUT is provided by APEX itself, so you might check for it in a condition, rather then defining the process as
unconditioned,justtopreventaccidentallogout.
So,thatsit.Justafewsimplemodificationstoyourcustomauthentication.Whatdoyouthink?Doesanybodyhaveamoreelegantsolution(Im
surethereare)?Iwouldappreciateit,ifyouwouldpostyourideasascommentstothisarticle.Ifyouhaventgotasolutionyet,butwanttouse
mine:goahead!Downherethelinksofthedemoapplicationonapex.oracle.comandthefulldownloadofitforyouasatemplate.
DemoandDownload
Trythedemoatapex.oracle.com!
(loginwithdemo/demo)
DownloadtheDemoApp!
(justimportandinstallincl.supportingobjectscripts
min.version:4.1
defaultlogin:demo/demo)
PossibleEnhancements:
Thewholemechanismisarathersimpleandnaveapproach.Ijustwantedtoexplainthebasicprincipleofit.Therearelotsofenhancementsand
improvementsonecouldthinkof,andactually,whilewritingthispostIthoughtofsomemyself:
usingpre/postfunctioncallofAuthenticationSchemainsteadofpageprocesses
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
4/7
9/13/2015
Oracle&ApexGeekery:RememberMeAPEXAutologin
integrateautologinlogicfrompage103topage101
cookienameapplicationvariableordynamicallygenerated
investigatingthepossibilityofanautologinauthenticationplugin
PostedbyChristianRokittaat4:21PM
Labels:APEX,autologin,login,remember
11comments:
David October15,2012at9:39PM
Thanksalotforthis.It'ssomethingI'vewantedforalongtime,buthavenevertakenthetimetoactuallyfigureoutandimplement!I've
added it to my site, but without pages 102 and 103 (some careful conditions on page 101 allow everything to coexist happily). Also
changedthepage0conditiontoonlyfireonpageswhichrequireauthentication.
Reply
ChristianRokitta
October15,2012at10:50PM
HiDavid,
Goodidea.Iwasthinkingofintegratingpage102and103too.
The reason I did not constrain the autologin to page that require authentication is, that I wanted returning users to be logged in
immediately,incaseIwantwanttoshowpersonalinformation,likenotifications,ormenuitems,thatotherwisewouldbehidden.Iguess
itdependsonthepurposeofyourwebsite/application.AsIsaid:it'satemplateorevenless,justahowto.
Regards,
Christian
Reply
RichardMartens October30,2012at10:19PM
HeyChristian,
Irememberthissubjectwasthefirstwehadadiscussionon,togetherwithSergeiinBrussels.Greatblog,I'llinvestigatesoon.
Regards,
Richard
Reply
DeanAttewell May8,2013at4:59AM
HiChristian
Icreatedamodifiedversionofwhatyouhave,itdoesn'thavepage0toredirecttoautologinpage.thiswascausingmeissues..
Ihave101,asmymainloginpage,(soApexautomaticallyredirectsto101(login)whennotauthenticated.butallitdoesischeckcookie
hastokenetc..
andifnovalidcookie/tokenitredirectstoanotherpagewithlogin/password,whereitsetstokencookie
Workswell
Dean
Reply
DeanAttewell May8,2013at5:03AM
HiChristian
Imadeamodifiedversionofyourlogin..afterhavingdifficultieswithpage0redirect..
Myversiondoesn'thavepage0redirect..
Imademystdloginpagetheautologinpage..soapexautomaticallygoestothispagewhennotauthenticated..
Andonlyruns1PL/SQL
DECLARE
cOWA_COOKIE.cookie
l_tokeneng_users.token%TYPE
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
5/7
9/13/2015
Oracle&ApexGeekery:RememberMeAPEXAutologin
l_usernameeng_users.username%TYPE
BEGIN
c:=OWA_COOKIE.get('REMEMBER_ME')
l_token:=c.vals(1)
Selectusername
intol_username
fromeng_users
wheretoken=l_token
IFlength(l_username)>0
THEN
APEX_CUSTOM_AUTH.post_login(l_username,V('APP_SESSION'),:APP_ID||':1',TRUE)
ELSE
apex_util.redirect_url('f?p=&APP_ID.:109:&SESSION.')
ENDIF
EXCEPTION
WHENOTHERS
THEN
apex_util.redirect_url('f?p=&APP_ID.:109:&SESSION.')
END
SoitredirectstoapagewithUsername/Passwordifnovalidcookie/tokenexists
Reply
joost May15,2013at4:51PM
HiChristian,
Thanksforyoutheblog.Itworksperfectonadesktopinterface.
Butonajquerymobileinterfaceitdoesn'tworkforme.
Doyouhaveanideahowtosolvethis.
Thanksinadvance.
Grtz,
Joost
Reply
Replies
ChristianRokitta
May16,2013at11:16AM
HiJoost,
IhavesuccessfullyimplementedtheapproachinanAPEX4.1applicationusingjQueryMobile:http://m.fifapex.net.
One thing to keep in mind: the standard jQM way of getting a new page is fetching it using an AJAX call. The autologin
functionality requires a HTTP call when logging in with the rememberme checkbox set, to set the tokencookie. In my
applicationIdisabledtheAJAXbehaviorfortheloginbuttonbyaddingajQMdataattributetoit:dataajax="false".
Hopethishelps.
Cheers,
Christian
Reply
joost May18,2013at10:41PM
HiChristian,
Thanksforyourquickresponse.
Indeedthissolvestheproblem.
Grtz,
joost
Reply
FarazBaloch March29,2014at12:29PM
HiChristian,
Imfacingproblemafterimportingthescriptintoapex.Whenitrytoconnecttotheapplicationusingthegivencredentials,igetanerro
"InvalidLoginCredentials,Waitfor40seconds".
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
6/7
9/13/2015
Oracle&ApexGeekery:RememberMeAPEXAutologin
Secondly, why are we using apex_authentication package for validation and how my_custome_users table is populated and how it is
validatedattherelogintimeofuser.
Regards
FarazSaleem
Reply
Replies
ChristianRokitta
April3,2014at11:17AM
HiFaraz,
Let'sdiscussthisoffline.Justsendmeanemail(christian@rokitta.nl)describingtheproblemyouarefacing.
Regards,
Christian
Reply
jeffkemponoracle.com August9,2014at4:58PM
Thanksverymuchforthis.Ireadthisbackin2012whenyoufirstposteditandputitinmylistofbookmarkstogettolaterwellIfinally
gotaroundtoit:)
Gotitworkingquitewell.Iendedupputtingtheautologincodejustonmyhomepages(desktopandmobileinterfaces)whichandputthe
AUTOLOGINandLOGOUTrequesthandlersontheloginpages,insteadofcreatingnewpagesforthesefunctions.
Apex4.2doesn'texposetheLogoutURLparameterintheauthenticationschemesoIjustchangedtheLogoutbuttonstonavigatetothe
loginpagewiththeLOGOUTrequest.
Reply
Enteryourcomment...
Commentas:
Publish
GoogleAccount
Preview
NewerPost
Home
OlderPos
Subscribeto:PostComments(Atom)
PoweredbyBlogger.
http://rokitta.blogspot.in/2012/10/remembermeapexautologin.html
7/7