Use Karaf’s JAAS implementation in your own Bundle

This article acts as both a help for people and as a reminder for myself (just in case).

So, I have a REST API based on Jersey 1.x that runs inside Apache Karaf. And I would like to add authentication for this REST API. The most important part is that the authentication should be delegated to Karaf. Indeed, Karaf provides an extensible and easy-to- use solution to authenticate with various backends: properties files, LDAP, databases, etc.

Personally, I was not an expert with JAAS (JAAS is the framework used by Karaf to manage users, roles, and in a more general way, authentication and authorizations). I spent a couple of hours to find how to easily plug with Karaf’s JAAS implementation. And believe or not, but the solution is very easy.

Here is a code snippet to put in your bundle, and that’s it!

public void authenticate( String user, String pwd, String realm ) throws LoginException {

	// If the authentication fails, a LoginException will be thrown
	LoginContext loginCtx = new LoginContext( realm, new RoboconfCallbackHandler( user, pwd ));

* A callback handler for JAAS.
static final class RoboconfCallbackHandler implements CallbackHandler {
	private final String username, password;

	 * Constructor.
	 * @param username
	 * @param password
	public RoboconfCallbackHandler( String username, String password ) {
		this.username = username;
		this.password = password;

	public void handle( Callback[] callbacks ) throws IOException, UnsupportedCallbackException {

		for( Callback callback : callbacks ) {
			if (callback instanceof NameCallback )
				((NameCallback) callback).setName( this.username );
			else if( callback instanceof PasswordCallback )
				((PasswordCallback) callback).setPassword( this.password.toCharArray());
				throw new UnsupportedCallbackException( callback );

By default, the configured REALM in Karaf is named “karaf”. It is based on properties files. So, you can test the code above with authenticate( “karaf”, “karaf”, “karaf” ). REALMs configuration is then documented on Karaf’s web site.

About this entry