1 18 package org.apache.activemq.security; 19 20 import java.util.Iterator ; 21 import java.util.Set ; 22 23 import javax.security.auth.Subject ; 24 import javax.security.auth.login.LoginContext ; 25 26 import org.apache.activemq.broker.Broker; 27 import org.apache.activemq.broker.BrokerFilter; 28 import org.apache.activemq.broker.ConnectionContext; 29 import org.apache.activemq.command.ConnectionInfo; 30 31 import org.apache.activemq.jaas.JassCredentialCallbackHandler; 32 33 import java.util.concurrent.CopyOnWriteArrayList ; 34 35 36 41 public class JaasAuthenticationBroker extends BrokerFilter { 42 43 private final String jassConfiguration; 44 private final CopyOnWriteArrayList securityContexts = new CopyOnWriteArrayList (); 45 46 public JaasAuthenticationBroker(Broker next, String jassConfiguration) { 47 super(next); 48 this.jassConfiguration = jassConfiguration; 49 } 50 51 static class JaasSecurityContext extends SecurityContext { 52 53 private final Subject subject; 54 55 public JaasSecurityContext(String userName, Subject subject) { 56 super(userName); 57 this.subject = subject; 58 } 59 60 public Set getPrincipals() { 61 return subject.getPrincipals(); 62 } 63 64 } 65 66 public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { 67 68 if( context.getSecurityContext()==null ) { 69 ClassLoader original = Thread.currentThread().getContextClassLoader(); 71 Thread.currentThread().setContextClassLoader(JaasAuthenticationBroker.class.getClassLoader()); 72 try { 73 try { 75 JassCredentialCallbackHandler callback = new JassCredentialCallbackHandler(info.getUserName(), info.getPassword()); 76 LoginContext lc = new LoginContext (jassConfiguration, callback); 77 lc.login(); 78 Subject subject = lc.getSubject(); 79 80 SecurityContext s = new JaasSecurityContext(info.getUserName(), subject); 81 context.setSecurityContext(s); 82 securityContexts.add(s); 83 } catch (Exception e) { 84 throw (SecurityException )new SecurityException ("User name or password is invalid.").initCause(e); 85 } 86 } finally { 87 Thread.currentThread().setContextClassLoader(original); 88 } 89 } 90 super.addConnection(context, info); 91 } 92 93 public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { 94 super.removeConnection(context, info, error); 95 if( securityContexts.remove(context.getSecurityContext()) ) { 96 context.setSecurityContext(null); 97 } 98 } 99 100 104 public void refresh() { 105 for (Iterator iter = securityContexts.iterator(); iter.hasNext();) { 106 SecurityContext sc = (SecurityContext) iter.next(); 107 sc.getAuthorizedReadDests().clear(); 108 sc.getAuthorizedWriteDests().clear(); 109 } 110 } 111 } 112 | Popular Tags |