BaseJmxAuthenticator.java

package com.ziesemer.utils.jmx.server.authentication;

import javax.management.remote.JMXAuthenticator;
import javax.security.auth.Subject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Mark A. Ziesemer
 * 	<a href="http://www.ziesemer.com.">&lt;www.ziesemer.com&gt;</a>
 */
public abstract class BaseJmxAuthenticator implements JMXAuthenticator{
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	public Subject authenticate(final Object credentials){
		try{
			if(!(credentials instanceof String[])){
				if(credentials == null){
					throw new SecurityException("Credentials required.");
				}
				throw new SecurityException(
					"Credentials must be String[], not " + credentials + ".");
			}
			final String[] credStrs = (String[])credentials;
			if(credStrs.length != 2){
				throw new SecurityException(
					"Credentials must be String[2], not String[" + credStrs.length + "].");
			}
			
			final String username = credStrs[0];
			final String password = credStrs[1];
			
			logger.debug("Authenticating: {}", username);
			
			final Subject subject = authenticate(username, password);
			if(subject != null){
				return subject;
			}
			throw new SecurityException("Invalid credentials.");
		}catch(final SecurityException se){
			logger.warn(se.toString());
			throw se;
		}
		
	}
	
	protected abstract Subject authenticate(String username, String password);
}