package org.jboss.jmx.connector.invoker;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.Principal;
import javax.management.ObjectName;
import javax.security.auth.Subject;
import org.jboss.mx.interceptor.AbstractInterceptor;
import org.jboss.mx.interceptor.Interceptor;
import org.jboss.mx.server.Invocation;
public class AuthorizationInterceptor extends AbstractInterceptor
{
private Object authenticator = null;
private Method authorize;
public AuthorizationInterceptor()
{
super();
try
{
setAuthorizingClass(RolesAuthorization.class);
}
catch(Exception e)
{
}
}
public void setAuthorizingClass(Class clazz)
throws Exception
{
authenticator = clazz.newInstance();
log.debug("Loaded authenticator: "+authenticator);
Class[] sig = {Principal.class, Subject.class, String.class, String.class};
authorize = clazz.getMethod("authorize", sig);
log.debug("Found authorize(Principal, Subject, String, String)");
}
public Object invoke(Invocation invocation) throws Throwable
{
String type = invocation.getType();
if (type == Invocation.OP_INVOKE)
{
String opName = invocation.getName();
if (opName.equals("invoke"))
{
Object[] args = invocation.getArgs();
org.jboss.invocation.Invocation inv = (org.jboss.invocation.Invocation) args[0];
Principal caller = inv.getPrincipal();
Object[] obj = inv.getArguments();
ObjectName objname = (ObjectName) obj[0];
String opname = (String) obj[1];
try
{
checkAuthorization(caller, objname.getCanonicalName(), opname);
}
catch(SecurityException e)
{
throw e;
}
catch(Exception e)
{
String msg = "Failed to authorize principal=" + caller
+ ",MBean=" + objname + ", Operation=" + opname;
SecurityException ex = new SecurityException(msg);
ex.initCause(e);
throw ex;
}
}
}
Interceptor i = invocation.nextInterceptor();
return i.invoke(invocation);
}
private void checkAuthorization(Principal caller, String objname, String opname)
throws Exception
{
Subject subject = SecurityActions.getActiveSubject();
if( subject == null )
throw new SecurityException("No active Subject found, add th AuthenticationInterceptor");
try
{
Object[] args = {caller, subject, objname, opname};
authorize.invoke(authenticator, args);
}
catch(InvocationTargetException e)
{
Throwable t = e.getTargetException();
if( t instanceof Exception )
throw (Exception) t;
else
throw new UndeclaredThrowableException(t);
}
}
}