001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.activemq.broker; 018 019import java.util.Set; 020import org.apache.activemq.command.Message; 021import org.apache.activemq.jaas.UserPrincipal; 022import org.apache.activemq.security.SecurityContext; 023 024/** 025 * This broker filter will append the producer's user ID into the JMSXUserID header 026 * to allow folks to know reliably who the user was who produced a message. 027 * Note that you cannot trust the client, especially if working over the internet 028 * as they can spoof headers to be anything they like. 029 * 030 * 031 */ 032public class UserIDBroker extends BrokerFilter { 033 boolean useAuthenticatePrincipal = false; 034 public UserIDBroker(Broker next) { 035 super(next); 036 } 037 038 public void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception { 039 final ConnectionContext context = producerExchange.getConnectionContext(); 040 if(context.isNetworkConnection() && messageSend.getUserID() != null) { 041 super.send(producerExchange, messageSend); 042 return; 043 } 044 String userID = context.getUserName(); 045 if (isUseAuthenticatePrincipal()) { 046 SecurityContext securityContext = context.getSecurityContext(); 047 if (securityContext != null) { 048 Set<?> principals = securityContext.getPrincipals(); 049 if (principals != null) { 050 for (Object candidate : principals) { 051 if (candidate instanceof UserPrincipal) { 052 userID = ((UserPrincipal)candidate).getName(); 053 break; 054 } 055 } 056 } 057 } 058 } 059 messageSend.setUserID(userID); 060 super.send(producerExchange, messageSend); 061 } 062 063 064 public boolean isUseAuthenticatePrincipal() { 065 return useAuthenticatePrincipal; 066 } 067 068 public void setUseAuthenticatePrincipal(boolean useAuthenticatePrincipal) { 069 this.useAuthenticatePrincipal = useAuthenticatePrincipal; 070 } 071}