• Home
  • RSS Feed
  • Log in

Wicket, JBoss, JAAS, LDAP
Posted by Serge Beaumont in the early afternoon: May 8th, 2008

Call me old-skool, but I don't like pulling in huge frameworks like Acegi for some simple authentication and authorization stuff. This post will show you how I connected Wicket security to an LDAP through JAAS. This leverages the LDAP configuration and access on the appserver level and keeps the application clean. This was done on JBoss, so YMMV on another server, but this post should help you along when you need to tweak the solution.

Caveat: this solution does NOT get you logged in as far as the appserver is concerned, so you'll not be able to use container calls like isUserInRole(). If you find out how, let me know. For our purposes we didn't need it, but it's nice to know anyway.

Step one: Set up the LDAP server

Download OpenLDAP and install it. You'll need to tweak the slapd.conf a bit. Things to set are the suffix, rootdn (this user will be used by JBoss to connect), rootpw, and optionally the directory.

(..snip..)

#######################################################################
# ldbm database definitions
#######################################################################

database	bdb
suffix		"dc=example,dc=com"
rootdn        	"cn=Manager,dc=example,dc=com"
# Cleartext passwords, especially for the rootdn, should
# be avoid.  See slappasswd(8) and slapd.conf(5) for details.
# Use of strong authentication encouraged.
rootpw       	secret
# The database directory MUST exist prior to running slapd AND
# should only be accessible by the slapd and slap tools.
# Mode 700 recommended.
directory	/my/custom/openldap/data/directory
# Indices to maintain
index	objectClass	eq

(..snip..)

When you run OpenLDAP, it can be handy to use a port higher than 1024 (don't need root privileges) and reference your custom slapd.conf file:

 
/path/to/slapd -h "ldap://127.0.0.1:10389" -f /path/to/my/custom/slapd.conf
 

You'll need to have the necessary user and group entries in the LDAP. I've attached the ldap-setup.ldif file that has a structure that corresponds to the configuration we'll set up in JBoss.

Step Two: Connect JBoss to the LDAP

JBoss uses the LdapLoginModule to work with an LDAP. You need to set up an application-policy in the login-config.xml that can be found in the JBOSS_HOME/server/default/conf directory. This will allow JBoss to log in to the LDAP server, and tells it what the structure of your LDAP is so the username, password and roles can be found.

I've attached a JBoss login-config.xml snippet.

 
<policy>
	<application-policy name = "mysecuritydomain">
		[..snip..]
	</application-policy>
 
	[...etcetera...]
</policy>
 

After setting this up you will be able to connect to the LDAP in your code through JAAS. The connection with your configuration is through the application policy name that is passed to the LoginContext() constructor (see later).

Step 3: The JAAS connector code

This code has been integrated into the Wicket security model, but it could be used anywhere. It checks the username/password and retrieves the user's roles through JAAS.

I've attached the class that does this and commented it (JAASBasedSession.java), but overall it does the following:

  • Create a handler for callbacks from JAAS. This handler knows the username/password.
  • Create a LoginContext using the name of your application-policy.
  • Call login(), which will lead to callbacks.
  • Retrieve and parse the subject information to get the roles that the user is authorized for.
  • Put the roles where Wicket can get at them.

Step 4: Integration with Wicket

The Wicket model depends on the retrieval of role names that a user is authorized for. Instead of subclassing from WebApplication, you subclass from AuthenticatedWebApplication. You will have two more methods to implement. One returns the class of the login page, the other returns the class of the AuthenticatedWebSession subclass that will be used by the framework. The AuthenticatedWebSession subclass is the one with the JAAS connector code, and it is queried by Wicket to retrieve the logged in user's roles.

 
package com.example.myapplication.ui;
 
[..snip..]
import org.apache.wicket.authentication.AuthenticatedWebApplication;
import org.apache.wicket.authentication.AuthenticatedWebSession;
[..snip..]
 
public class MyWicketApplication extends AuthenticatedWebApplication {
 
	[...other stuff...]
 
    @Override
    protected void init() {
        super.init();
 
		[...other stuff...]
 
        // setting page that Wicket will display if user has no rights to access a page
        getApplicationSettings().setAccessDeniedPage(LoginPage.class);
 
        mountBookmarkablePage("/login", LoginPage.class);
    }
 
    protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
        return JAASBasedSession.class;
    }
 
    protected Class<? extends WebPage> getSignInPageClass() {
        return LoginPage.class;
    }
 
	[...other stuff...]
}
 

The commented JAASBasedSession.java is attached. The LoginPage.java I've attached is likely not the most elegant way to log into Wicket. It works, but refactoring it is a bit lower on my to-do list.

Step 5: Annotate your secure pages

Wicket has annotations that check if the user has the roles required for that page. These role names map to the roles as they have been set in the LDAP.

 
package com.example.myapplication.admin.ui;
 
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.WebPage;
 
// The AuthorizeInstantiation annotation enforces security based on the roles that have been
// set in the Session and are retrieved with the getRoles() method. In this case both
// admin roles are authorized to use the page. For a single role you don't need the curly braces.
 
@AuthorizeInstantiation({"TechnicalAdmin","FunctionalAdmin"})
public class AdministrationPage extends WebPage {
 
	[..snip..]
 
}
 

Step 6: World domination!

By now you should have a complete setup. You can authenticate and authorize your Wicket application, while keeping your application free of the specifics of the LDAP setup. All that rests is teaching your users not to use "secret" as their password... :-)

  • Share/Bookmark

Filed under Java, Security | 3 Comments »



3 Responses to “Wicket, JBoss, JAAS, LDAP”



    Erik Pragt Says:
    Posted at: May 8, 2008 at 3:42 pm

    Hi Serge,

    In JBoss 4.2.2, you can get logged into the Application Server by using the WebAuthentication class. It’s located in JBoss, in the jbossweb-service.jar file. It’s not on a Maven Repository as far as I know, so you have to install it manually.

    You can use it something like:

        private boolean authenticateForContainer(String username, String password) {
            WebAuthentication webAuthentication = new WebAuthentication();
            return webAuthentication.login(username, password);
        }
    

    I have no idea on how to to this in older versions of JBoss!

    You can find more information about it here: http://roneiv.wordpress.com/2008/03/15/using-webauthentication-in-jboss/



    Serge Beaumont Says:
    Posted at: May 9, 2008 at 1:41 am

    Erik,

    I tried that option, but for some reason it did not work: isUserInRole() calls still failed on everything. This could mean that WebAuthentication does exactly that: authenticate, but no authorization.



    Laurent Says:
    Posted at: June 15, 2009 at 8:50 am

    Hi,

    Works great. Thanks for posting it.

    Unless I missed something I didn’t find a wicket build-in getter for “username”
    So, I’ve added private variable “username” next to roles and a getUsername().

    Laurent



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Training

  • Enterprise Java Security Applied
    Custom made, in-company

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    Architecture Groovy Poppendieck product owner Xebia Agile esb Performance Hibernate Seam Scala Closures Functional Programming XML Semantic Web fitnesse Testing Spring Agile Awareness Workshop Java Scrum JavaOne SOA Lean IntelliJ Grails Ajax qcon Introduction to Agile Maven
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs