下面列出了怎么用javax.jms.JMSSecurityException的API类实例代码及写法,或者点击链接到github查看源代码。
private void ensureConnected() throws JMSException {
if (isConnected() || closed.get()) {
return;
}
synchronized(this.connectionId) {
if (isConnected() || closed.get()) {
return;
}
if (clientID == null || clientID.trim().isEmpty()) {
throw new IllegalArgumentException("Client ID cannot be null or empty string");
}
if (!user.isValid()) {
executor.shutdown();
throw new JMSSecurityException(user.getFailureCause());
}
connected.set(true);
}
}
private MockJMSConnection createMockConnection(String username, String password) throws JMSException {
MockJMSUser user = validateUser(username, password);
if (!user.isValid() && !deferAuthenticationToConnection) {
throw new JMSSecurityException(user.getFailureCause());
}
MockJMSConnection connection = new MockJMSConnection(user);
if (clientID != null && !clientID.isEmpty()) {
connection.setClientID(clientID, true);
} else {
connection.setClientID(UUID.randomUUID().toString(), false);
}
try {
connection.initialize();
} catch (JMSException e) {
connection.close();
}
return connection;
}
@Test
public void testAutoCreateOnSendToQueueSecurity() throws Exception {
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addUser("guest", "guest");
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().setDefaultUser("guest");
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addRole("guest", "rejectAll");
Role role = new Role("rejectAll", false, false, false, false, false, false, false, false, false, false);
Set<Role> roles = new HashSet<>();
roles.add(role);
server.getSecurityRepository().addMatch("#", roles);
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = ActiveMQJMSClient.createQueue(QUEUE_NAME);
try {
session.createProducer(queue);
Assert.fail("Sending a message here should throw a JMSSecurityException");
} catch (Exception e) {
Assert.assertTrue(e instanceof JMSSecurityException);
}
connection.close();
}
@Test
public void testTemporaryQueue() throws Exception {
ConnectionFactory connectionFactory = getConnectionFactory("a", "a");
String message = "blah";
//Expect to be able to create subscriber on pre-defined/existing queue.
String messageRecieved = sendAndReceiveText(connectionFactory, "clientId", message, s -> s.createTemporaryQueue(), (d, s) -> s.createConsumer(d));
Assert.assertEquals(message, messageRecieved);
connectionFactory = getConnectionFactory("c", "c");
try {
sendAndReceiveText(connectionFactory, "clientId", message, s -> s.createTemporaryQueue(), (d, s) -> s.createConsumer(d));
Assert.fail("Security exception expected, but did not occur, excepetion expected as not permissioned to create a temporary queue");
} catch (JMSSecurityException jmsse) {
} catch (JMSException e) {
e.printStackTrace();
Assert.fail("thrown a JMSEXception instead of a JMSSEcurityException");
}
}
@Test
public void testTemporaryTopic() throws Exception {
ConnectionFactory connectionFactory = getConnectionFactory("a", "a");
String message = "blah";
//Expect to be able to create subscriber on pre-defined/existing queue.
String messageRecieved = sendAndReceiveText(connectionFactory, "clientId", message, s -> s.createTemporaryTopic(), (d, s) -> s.createConsumer(d));
Assert.assertEquals(message, messageRecieved);
connectionFactory = getConnectionFactory("c", "c");
try {
sendAndReceiveText(connectionFactory, "clientId", message, s -> s.createTemporaryTopic(), (d, s) -> s.createConsumer(d));
Assert.fail("Security exception expected, but did not occur, excepetion expected as not permissioned to create a temporary queue");
} catch (JMSSecurityException jmsse) {
} catch (JMSException e) {
e.printStackTrace();
Assert.fail("thrown a JMSEXception instead of a JMSSEcurityException");
}
}
@Test
public void testSecureQueue() throws Exception {
ConnectionFactory connectionFactory = getConnectionFactory("b", "b");
String message = "blah";
//Expect to be able to create subscriber on pre-defined/existing queue.
String messageRecieved = sendAndReceiveTextUsingQueue(connectionFactory, "clientId", message, "secured_queue", (q, s) -> s.createConsumer(q));
Assert.assertEquals(message, messageRecieved);
connectionFactory = getConnectionFactory("a", "a");
messageRecieved = sendAndReceiveTextUsingQueue(connectionFactory, "clientId", message, "new-queue-1", (q, s) -> s.createConsumer(q));
Assert.assertEquals(message, messageRecieved);
connectionFactory = getConnectionFactory("b", "b");
try {
sendAndReceiveTextUsingQueue(connectionFactory, "clientId", message, "new-queue-2", (q, s) -> s.createConsumer(q));
Assert.fail("Security exception expected, but did not occur, excepetion expected as not permissioned to dynamically create address, or queue");
} catch (JMSSecurityException j) {
//Expected exception
}
connectionFactory = getConnectionFactory("a", "a");
messageRecieved = sendAndReceiveTextUsingQueue(connectionFactory, "clientId", message, "new-queue-2", (q, s) -> s.createConsumer(q));
Assert.assertEquals(message, messageRecieved);
}
@Test(timeout = 10000)
public void testNoUserOrPassword() throws Exception {
Connection connection = null;
try {
connection = createConnection("", "", null, false);
connection.start();
fail("Expected JMSException");
} catch (JMSSecurityException ex) {
instanceLog.debug("Failed to authenticate connection with no user / password.", ex);
} finally {
if (connection != null) {
connection.close();
}
}
}
@Test(timeout = 30000)
public void testRepeatedWrongPasswordAttempts() throws Exception {
for (int i = 0; i < 25; ++i) {
Connection connection = null;
try {
connection = createConnection(fullUser, "wrongPassword", null, false);
connection.start();
fail("Expected JMSException");
} catch (JMSSecurityException ex) {
instanceLog.debug("Failed to authenticate connection with incorrect password.");
} finally {
if (connection != null) {
connection.close();
}
}
}
}
@Test(timeout = 30000)
public void testConsumerNotAuthorized() throws Exception {
Connection connection = createConnection(noprivUser, noprivPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
try {
session.createConsumer(queue);
fail("Should not be able to consume here.");
} catch (JMSSecurityException jmsSE) {
instanceLog.debug("Caught expected exception");
}
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testBrowserNotAuthorized() throws Exception {
Connection connection = createConnection(noprivUser, noprivPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
try {
QueueBrowser browser = session.createBrowser(queue);
// Browser is not created until an enumeration is requesteda
browser.getEnumeration();
fail("Should not be able to consume here.");
} catch (JMSSecurityException jmsSE) {
instanceLog.debug("Caught expected exception");
}
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testConsumerNotAuthorizedToCreateQueues() throws Exception {
Connection connection = createConnection(noprivUser, noprivPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName(getPrecreatedQueueSize() + 1));
try {
session.createConsumer(queue);
fail("Should not be able to consume here.");
} catch (JMSSecurityException jmsSE) {
instanceLog.debug("Caught expected exception");
}
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testProducerNotAuthorized() throws Exception {
Connection connection = createConnection(guestUser, guestPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
try {
session.createProducer(queue);
fail("Should not be able to produce here.");
} catch (JMSSecurityException jmsSE) {
instanceLog.debug("Caught expected exception");
}
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testAnonymousProducerNotAuthorized() throws Exception {
Connection connection = createConnection(guestUser, guestPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(null);
try {
producer.send(queue, session.createTextMessage());
fail("Should not be able to produce here.");
} catch (JMSSecurityException jmsSE) {
instanceLog.debug("Caught expected exception");
}
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testCreateTemporaryQueueNotAuthorized() throws JMSException {
Connection connection = createConnection(guestUser, guestPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try {
session.createTemporaryQueue();
} catch (JMSSecurityException jmsse) {
instanceLog.debug("Client should have thrown a JMSSecurityException but only threw JMSException");
}
// Should not be fatal
assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testCreateTemporaryTopicNotAuthorized() throws JMSException {
Connection connection = createConnection(guestUser, guestPass);
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try {
session.createTemporaryTopic();
} catch (JMSSecurityException jmsse) {
instanceLog.debug("Client should have thrown a JMSSecurityException but only threw JMSException");
}
// Should not be fatal
assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
} finally {
connection.close();
}
}
/**
* Login with valid user and password
* But try send to address not authorised - Persistent
* Should not allow and should throw exception
*/
@Test
public void testLoginValidUserAndPasswordButNotAuthorisedToSend() throws Exception {
SimpleString queueName = SimpleString.toSimpleString("guest.cannot.send");
if (getJmsServer().locateQueue(queueName) == null) {
getJmsServer().createQueue(new QueueConfiguration(queueName).setRoutingType(RoutingType.ANYCAST));
}
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = connectionFactory.createConnection("guest", "guest");
Session session = connection.createSession();
Destination destination = session.createQueue(queueName.toString());
MessageProducer messageProducer = session.createProducer(destination);
try {
messageProducer.send(session.createTextMessage("hello"));
fail("JMSSecurityException expected as guest is not allowed to send");
} catch (JMSSecurityException activeMQSecurityException) {
//pass
}
connection.close();
}
private void doSaslFailureCodesTestImpl(UnsignedByte saslFailureCode) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslFailingExchange(new Symbol[] {PLAIN, ANONYMOUS}, PLAIN, saslFailureCode);
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?jms.clientID=myClientID");
try {
factory.createConnection("username", "password");
fail("Excepted exception to be thrown");
}catch (JMSSecurityException jmsse) {
LOG.info("Caught expected security exception: {}", jmsse.getMessage());
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
private void doMechanismSelectedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, boolean wait) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslFailingAuthentication(serverMechs, clientSelectedMech);
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?jms.clientID=myclientid");
try {
factory.createConnection(username, password);
fail("Excepted exception to be thrown");
}catch (JMSSecurityException jmsse) {
// Expected, we deliberately failed the SASL process,
// we only wanted to verify the correct mechanism
// was selected, other tests verify the remainder.
LOG.info("Caught expected security exception: {}", jmsse.getMessage());
}
if (wait) {
Thread.sleep(200);
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
private void doMechanismSelectionRestrictedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, String mechanismsOptionValue) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslFailingAuthentication(serverMechs, clientSelectedMech);
String uriOptions = "?jms.clientID=myclientid";
if(mechanismsOptionValue != null) {
uriOptions += "&amqp.saslMechanisms=" + mechanismsOptionValue;
}
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);
try {
factory.createConnection(username, password);
fail("Excepted exception to be thrown");
}catch (JMSSecurityException jmsse) {
// Expected, we deliberately failed the SASL process,
// we only wanted to verify the correct mechanism
// was selected, other tests verify the remainder.
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 20000)
public void testSaslGssApiKrbConfigError() throws Exception {
final String loginConfigScope = "KRB5-CLIENT-DOES-NOT-EXIST";
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslGSSAPIFail();
String uriOptions = "?sasl.options.configScope=" + loginConfigScope + "&amqp.saslMechanisms=" + GSSAPI;
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);
factory.createConnection();
fail("Expect exception on no login config");
} catch (JMSSecurityException expected) {
assertTrue(expected.getMessage().contains(loginConfigScope));
}
}
private void doMechanismSelectedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, boolean enableGssapiExplicitly) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslFailingAuthentication(serverMechs, clientSelectedMech);
String uriOptions = "?jms.clientID=myclientid";
if(enableGssapiExplicitly) {
uriOptions += "&amqp.saslMechanisms=PLAIN," + GSSAPI;
}
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);
try {
factory.createConnection(username, password);
fail("Excepted exception to be thrown");
}catch (JMSSecurityException jmsse) {
// Expected, we deliberately failed the SASL process,
// we only wanted to verify the correct mechanism
// was selected, other tests verify the remainder.
LOG.info("Caught expected security exception: {}", jmsse.getMessage());
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test
public void testContextClosePreservesSessionCloseException() throws JMSException {
JmsConnection connection = Mockito.mock(JmsConnection.class);
JmsSession session = Mockito.mock(JmsSession.class);
Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE);
Mockito.doThrow(IllegalStateException.class).when(session).close();
Mockito.doThrow(JMSSecurityException.class).when(connection).close();
context.createTemporaryTopic();
Mockito.verify(connection, Mockito.times(1)).createSession(JMSContext.AUTO_ACKNOWLEDGE);
try {
context.close();
fail("Should throw ISRE");
} catch (IllegalStateRuntimeException isre) {
}
}
private void doConnectThrowsSecurityViolationOnFailureFromSaslWithOrExplicitlyWithoutClientIDTestImpl(boolean clientID, UnsignedByte saslFailureCode) throws Exception {
String optionString;
if (clientID) {
optionString = "?jms.clientID=myClientID";
} else {
optionString = "?jms.awaitClientID=false";
}
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslFailingExchange(new Symbol[] {PLAIN, ANONYMOUS}, PLAIN, saslFailureCode);
ConnectionFactory factory = new JmsConnectionFactory("failover:(amqp://localhost:" + testPeer.getServerPort() + ")" + optionString);
try {
factory.createConnection("username", "password");
fail("Excepted exception to be thrown");
}catch (JMSSecurityException jmsse) {
LOG.info("Caught expected security exception: {}", jmsse.getMessage());
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
private void doConnectThrowsSecurityViolationOnFailureFromSaslImplicitlyWithoutClientIDTestImpl(UnsignedByte saslFailureCode) throws Exception {
try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
testPeer.expectSaslFailingExchange(new Symbol[] {PLAIN, ANONYMOUS}, PLAIN, saslFailureCode);
ConnectionFactory factory = new JmsConnectionFactory("failover:(amqp://localhost:" + testPeer.getServerPort() + ")");
Connection connection = factory.createConnection("username", "password");
try {
connection.start();
fail("Excepted exception to be thrown");
}catch (JMSSecurityException jmsse) {
LOG.info("Caught expected security exception: {}", jmsse.getMessage());
}
testPeer.waitForAllHandlersToComplete(1000);
}
}
@Test(timeout = 30000)
public void testAnonymousProducerNotAuthorized() throws Exception {
connection = createAmqpConnection("guest", "password");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("USERS.txQueue");
MessageProducer producer = session.createProducer(null);
try {
producer.send(queue, session.createTextMessage());
fail("Should not be able to produce here.");
} catch (JMSSecurityException jmsSE) {
LOG.info("Caught expected exception");
} catch (JMSException jms) {
LOG.info("Caught expected exception");
}
}
public void checkCanProduce(MockJMSDestination destination) throws JMSSecurityException {
if (destination == null) {
if (isCanProducerAnonymously()) {
return;
} else {
throw new JMSSecurityException("User " + username + " not allowed for create anonymous producers.");
}
}
if (!isCanProduceAll() && !writableDestinations.contains(destination.getName())) {
throw new JMSSecurityException("User " + username + " cannot read from destination: " + destination.getName());
}
}
@Test
public void testCreateUsesCauseIfJMSExceptionPresent() {
IOException ioe = new IOException("Ignore me", new JMSSecurityException("error"));
JMSException result = JMSExceptionSupport.create(ERROR_MESSAGE, ioe);
assertNotNull(result);
assertTrue(result instanceof JMSSecurityException);
}
@Test
public void testConnectionCreateAuthentication() throws JMSException {
try {
cf.createConnection("admin", "admin");
} catch (JMSSecurityException jmsse) {
fail("Should not be able to create connection using bad credentials");
}
assertEquals(1, cf.getNumConnections());
}
@Test
public void testConnectionCreateAuthenticationError() throws JMSException {
try {
cf.createConnection("guest", "guest");
fail("Should not be able to create connection using bad credentials");
} catch (JMSSecurityException jmsse) {}
assertEquals(0, cf.getNumConnections());
}
@Test
public void testFailedCreateConsumerConnectionStillWorks() throws JMSException {
// User can write but not read
user.setCanConsumeAll(false);
Connection connection = null;
try {
connection = cf.createConnection("admin", "admin");
} catch (JMSSecurityException jmsse) {
fail("Should not be able to create connection using bad credentials");
}
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("test");
try {
session.createConsumer(queue);
fail("Should fail to create consumer");
} catch (JMSSecurityException ex) {
LOG.debug("Caught expected security error");
}
MessageProducer producer = session.createProducer(queue);
producer.close();
connection.close();
}