How JAAS enables use of custom security repositories with J2EE applications.docx
《How JAAS enables use of custom security repositories with J2EE applications.docx》由会员分享,可在线阅读,更多相关《How JAAS enables use of custom security repositories with J2EE applications.docx(11页珍藏版)》请在冰豆网上搜索。
![How JAAS enables use of custom security repositories with J2EE applications.docx](https://file1.bdocx.com/fileroot1/2022-11/23/355c2dd4-1500-4daf-ba2c-3aa05343611a/355c2dd4-1500-4daf-ba2c-3aa05343611a1.gif)
HowJAASenablesuseofcustomsecurityrepositorieswithJ2EEapplications
ThistutorialdescribeshowadevelopercanwriteacustomJAASLoginModuleforusinganLDAPauthenticationdatastorealongwithaJava2Platform,EnterpriseEdition(J2EE)application.
ThetutorialincludesasampleimplementationofanLDAPbasedLoginModulewhichisdownloadableasjaastutorial.zip.
WhyJAASinJ2EE
OneofthelimitationsoftheJ2EEversion1.2platformwasthatitdidnotprovideapplicationdeveloperswithastandardrouteforintegratingtheapplicationserverrealmwithexistingorcustomsecurityinfrastructures.J2EEversion1.3nowsolvesthatwiththeinclusionoftheJavaAuthenticationandAuthorizationService(JAAS)framework.ReadmoreonJAAShere.
J2EEapplicationserversthatimplementJAASprovideenterpriseapplicationdeveloperswiththestandardLoginModuleAPIfortappingcustomorlegacysecuritysystemsfromtheirapplications.WhileapplicationdeveloperswritetotheLoginModuleAPI(specifically,theLoginContextAPI),theapplicationserverimplementstheLoginModuleinterface.
Thestandards-basedLoginModuleinterfacegivesJ2EEdevelopersthefreedomtotapavarietyofinformationsourcesthatuseJavaDatabaseConnectivity,thelightweightdirectoryaccessprotocol(LDAP),orSharedFileSystemstostoreauthenticationdata,withoutrequiringthemtomodifytheapplicationcode.Indeed,thereareanincreasingnumberofscenarioswhereJ2EEapplicationdeveloperswishtotapcustomauthenticationrepositoriesfromtheirapplications.TheywoulddothisbywritingaLoginModule,packagingitalongwiththeirapplication,anddistributingittotargetJ2EEapplicationserversinaprescribedway.
TheJ2EEModel:
Roles,UsersandJAAS
TheJ2EEmodeldefinessecurityattwolevels:
thesystemlevelandtheapplicationlevel.SystemlevelsecurityisdefinedintermsofUserGroups,calledRoles,andintermsofsecurityprivilegesmappingdefinitions,calledRealms.RealmsaremappingsofoneormoreUserGroupstoasetofprivilegesorpermissions.
ApplicationlevelsecurityisconstitutedfromUserGroupsandRealms.Attheapplicationlevel,securitypermissionsalsolistthevariousapplicationcomponentsthatareaccessiblebyeachUserGroupineachRealm.Thus,whenanapplicationisdeployed,itsapplicationlevelrealmsandrolesaremappedtothesystemlevelrealmsandrolesdefinedontheserver.
J2EEapplicationserversimplementingJAASenableapplicationdeveloperstowriteacustom"pluggable"loginmoduleintheserverenvironment.Suchamoduleprovidesaconduitforrolesdefinedinthepackagedapplicationtousergroupinformationstoredinsomecustomauthenticationrepository,suchasanLDAPserver.
HowaLoginModulehelpsapplicationrolesandgroupsmaptoauthenticationdatastoredinacustomrepositorysuchasLDAP.
HowJAASIntegrateswiththeAppServer
TheconstituentsoftheJAASsolutionare
∙LoginModule
∙ApplicationServer'sSecurityService
∙J2EEApplication
Thefollowinginteractiondiagramdepictsanoverviewoftheinteractionamongtheseconstituents.
WritingtheJAASSecurityModule
AJ2EEapplicationdeveloperwritingsecuritywithJAASwouldbasicallywritetheLoginModule,theJAASinterfaceimplementationthatholdstheauthenticationlogic.ApplicationserverstypicallyshipwithstandardLoginModuleimplementations.Applicationdevelopersmaywanttowritetheirownimplementationandwillseehowtodothistlthroughthefollowingsteps:
1.WritingtheLoginModuleinterface(LoginContextAPI)
2.WritingtheCallBackHandlerinterfacethatenablesclienttopassauthenticationdatatotheserver.
3.ConfiguringtheLoginModuleandCallBackHandlerwiththeserverandapplication.
4.Packagingtheapplicationalongwithmoduleclasses
5.IntegratingtheLoginModulewiththeapplicationserver
Step1:
WritingtheLoginModule
Inthistutorial,youwillseecodesnippetsfromaLoginModuleimplementationforanLDAPServer.WealsodemonstratehowtotesttheLDAPLoginModulesampleinatypicalJ2EEapplicationserverenvironment.
ThisishowtheLoginModuleimplementationclassisdefined:
publicclassLDAPLoginModuleimplementsLoginModule
ThestandardJAASpackagesrequiredbythisclassareimportedasshownhere:
importjavax.security.*;
StandardmethodsintheLoginModulethatmustbeimplementedare:
1.initialize()
2.login()
3.commit()
4.abort()
5.logout()
initialize()
Theinitializemethoddoesthefollowing:
1.SetsconfigurationsrequiredbytheLoginModule
2.CollectslogininformationthatisencapsulatedintheCallBackHandler
3.InitializesandinstantiatesallconfigurationparametersforthisinstanceoftheLoginModule
TheclientinstantiatestheLoginContextobjectandpassesaCallBackHandlerinstancewiththeusernameandpassword.WhentheLoginContextobjectisinstantiated,theinitialize()methodoftheLoginModuleistriggered.
publicstaticvoidmain(Stringargs[])
{
LoginContextlc=newLoginContext("Login",
newMyCallbackHandler(args[0],args[1]));
}
login()
Thismethodreturnsabooleanvariable,whichistrueiftheauthenticationinformationprovidedisvalid.Theloginmethodperformsthefollowingtasks:
1.Fetchesthelogininformation
2.Authenticatestheuser
ThelogininformationisfetchedusingtheCallBackHandler.Thecodethatdoesthisisshownhere:
Callback[]calls=newCallback[2];
calls[0]=newNameCallback("name");
calls[1]=newPasswordCallback("Password",false);
callbackHandler.handle(calls);
Theloginmethodtriestoconnecttotheserverusingthelogininformationthatisfetched.Iftheconnectionisestablished,themethodreturnsthevaluetrue.Thefollowingcodesnippetshowsthis:
booleanverification=false;
try{
props.put(Context.SECURITY_PRINCIPAL,cbUserName);
props.put(Context.SECURITY_CREDENTIALS,cbPassword);
ctx=newInitialDirContext(props);
verification=true;
}
returnverification;
ThiscodechangeswiththeactualtypeofsecurityframeworkforwhichtheLoginModuleiswritten.
commit()method
Thismethodsetsthesubjectinthesessiontotheusernamethatisvalidatedbytheloginmethod.ItalsopopulatesthesubjectwithrolesspecifiedintheLDAPserverforthatuser,andreturnstrue.Iftheuserisnotvalidated,thecommitmethodreturnsfalse.Thefollowingcodesnippetshowsthis:
if(verification)
{subject.getPrincipals().add(userName);
...subject.getPrincipals().add(role);
returntrue;
}elsereturnfalse;
abort()method
ThismethodisusedtoexittheLoginModuleincaseofruntimeexceptionsandisusuallytriggeredbytheapplicationserver.Thismethodisinvokedaftertheabort()methodofLoginContext.TheapplicationdevelopermustnotdirectlycalltheabortmethodoftheLoginContextinterface.
logout()method
Thismethodclearstheprincipalsettingsofthesubjectinthesession.Itremovestheprivilegesettingsassociatedwiththerolesofthesubject.Thefollowingcodesnippetshowsthis:
subject.getPrincipals().clear();
verification=false;
returntrue;
ExceptionsthrownbyLoginModulemethods
AccordingtotheJAASspecifications,allLoginModulemethodsshouldonlythrowaLoginException.AnyotherexceptionduringLoginModuleexecutionshouldbecaughtandaLoginExceptionthrownagainstit.Thefollowingcodesnippetshowshowthiscanbedone:
publicbooleanlogin()throwsLoginException
{
...
catch(IOExceptione)
{thrownewLoginException(e.toString());}
...}
Step2:
WritingtheCallBackHandler
TheCallBackHandleristheJAASinterfacethatdefinesthetypeofdatausedforauthentication.Forexample,ausername-passwordorauser-certificatecombinationformsasecurityidentityandcredentialpair.ThetypeofdatausedforvalidatingtheidentityisdefinedaspartoftheimplementationoftheCallBackHandlerinterface.
TheCallbackHandlerimplementationcontainsasinglemethod,handle().ThefollowingcodesnippetfromtheCallBackHandlerdistributedwiththesampleclientapplicationClientLoginSample.javademonstratesthis:
staticclassMyCallbackHandlerimplementsCallbackHandler
{
privateStringusername;
privateStringpassword;
Thehandle()methodsetsthevalueoftheusernameandpasswordattributes,passedbytheclientapplication,intheLoginModule'sCallBackHandler.Thefollowingcodesnippetshowsthis:
handle(){
...
if(callbacks[i]instanceofNameCallback){
NameCallbackncb=(NameCallback)callbacks[i];
ncb.setName(username);}
if(callbacks[i]instanceofPasswordCallback){
PasswordCallbackpcb=(PasswordCallback)callbacks[i];
pcb.setPassword(password.toCharArray());
}}
Step3:
ConfiguringtheJ2EEapplication
AJ2EEapplicationpackageincludesdescriptorsthatcontaininformationaboutsecurityprivilegesforvariousmodules/componentsoftheapplication.Asecurityprivilegeisdefinedattheapplicationlevelandisassociatedwithrealmsandroles.Duringdeployment,theserolesaremappedtorolesdefinedintheserver-levelrealm.
ConfiguringaloginmodulewithaJ2EEapplicationinvolvesthefollowingsteps:
1.CreatingaloginUIthatvalidatesuserinformationbycallingtheLoginContextinterface.
2.Creatingapplicationlevelrealmsandroles,andmappingpermissionstoapplicationcomponents.
3.DistributingtheLoginModuleclasseswiththeapplication.
Step4:
PackagingtheLoginModulealongwithApplication
AJ2EEapplicationdeveloperwouldwanttoconfiguretheLoginModulewithatargetJ2EEapplicationserver.Therefore,theLoginModule,alongwiththehelperclasses,ispackagedintoaseparateJARfilethatmaybedistributedindependentlyoftheapplicationarchives,andseparatelyloaded