exception - java access ldap server once the ldap server has been restarted - ldap

I have the next problem, I get a context from the LDAP setting Up JNDI Environment properties for the InitialContext as it showed below.
Then I restart the ldap server, and each time I try to get again the InitialContext, the next exception is thrown.
Code to get the Context.
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
ht.put(Context.SECURITY_PRINCIPAL,"USER1");
ht.put(Context.CREDENTIALS,"PASSWORD1");
try {
ctx = new InitialContext(ht);
}
catch (NamingException e) {
}
finally {
try {ctx.close();
}
catch (Exception e) {
// a failure occurred
}
}
Exception:
java.security.PrivilegedActionException: javax.naming.ConfigurationException: Call to NamingManager.getObjectInstance() failed:
[Root exception is java.lang.SecurityException:
[Security:090398]Invalid Subject: principals=[ADMIN]]; remaining name ''
BEA-090398

You are not providing a proper DN to authenticate with:
ht.put(Context.SECURITY_PRINCIPAL,"USER1");
You should have cn=user1,ou=something,dc=something,dc=com or the like.

Related

MassTransit ISendEndpoint.Send method doesn't throw exception when RabbitMQ is unreachable

Having the following code snippet:
try
{
UpdateCommand updateCommand = new UpdateCommand
{
Name = "Update"
};
await sendEndpoint.Send(updateCommand);
}
catch (BrokerUnreachableException ex)
{
}
catch (Exception ex)
{
}
When calling Send method and when there is no connection with RabbitMQ then exception is not being thrown. Is it supposed to work like this ?
I've tried to ConnectSendObserver to my ReceiveEndpoint like so:
ISendObserver sendObserver = new UpdateSendObserver();
cfg.ReceiveEndpoint(EventBusConstants.UpdateQueue, c => {
c.ConfigureConsumer<UpdateCommandConsumer> (ctx);
cfg.ConnectSendObserver(sendObserver);
});
But it doesn't hit any of the PreSend, PostSend, SendFault methods when there is no connection with RabbitMQ.
As explained in the GitHub Discussion, you can cancel the call to Send/Publish using a CancellationToken. The transport uses a retry policy if a connection to the broker is not available.

Unable to cleanup Infinispan DefaultCacheManager in state FAILED

I am getting this Exception when trying to restart CacheManager, that failed to start.
Caused by: org.infinispan.jmx.JmxDomainConflictException: ISPN000034: There's already a JMX MBean instance type=CacheManager,name="DefaultCacheManager" already registered under 'org.infinispan' JMX domain. If you want to allow multiple instances configured with same JMX domain enable 'allowDuplicateDomains' attribute in 'globalJmxStatistics' config element
at org.infinispan.jmx.JmxUtil.buildJmxDomain(JmxUtil.java:53)
I think it's a bug, but am I correct?
The version used is 9.0.0.Final.
EDIT
The error can be seen using this code snippet.
import org.infinispan.configuration.cache.*;
import org.infinispan.configuration.global.*;
import org.infinispan.manager.*;
class Main {
public static void main(String[] args) {
System.out.println("Starting");
GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
global.transport()
.clusterName("discover-service-poc")
.initialClusterSize(3);
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.REPL_SYNC);
DefaultCacheManager cacheManager = new DefaultCacheManager(global.build(), builder.build(), false);
try {
System.out.println("Starting cacheManger first time.");
cacheManager.start();
} catch (Exception e) {
e.printStackTrace();
cacheManager.stop();
}
try {
System.out.println("Starting cacheManger second time.");
System.out.println("startAllowed: " + cacheManager.getStatus().startAllowed());
cacheManager.start();
System.out.println("Nothing happening because in failed state");
System.out.println("startAllowed: " + cacheManager.getStatus().startAllowed());
} catch (Exception e) {
e.printStackTrace();
cacheManager.stop();
}
cacheManager = new DefaultCacheManager(global.build(), builder.build(), false);
cacheManager.start();
}
}

Has anyone ever got WS-Trust to work in JBoss 7?

I've literally tried everything under the sun to get token based WS-Trust Web Services to work, to no avail. I can obtain a token from an STS, but the life of me, I can not figure out how make the WS server secure and accessible from the outside using a token.
So what I would love to know, is if anyone has ever got this to work on JBoss 7. I'm not interested in "this and that on jboss should give you some information". Been there done that - doesn't work. Have YOU been able to get it to work?
I looked at picketlink to secure web services using SAML but it appears to be exposing the SAML authentication using a JAAS security context. So instead I just wrote a custom handler using the picketlink API to secure the WS. The handler essentially does the same thing (i.e. saml assertion expiration and digital signature validation check) as the SAMLTokenCertValidatingCommonLoginModule available in picketlink jars but passes the SAML attributes into WS message context instead of passing it along as a JAAS security context.
Find below the code snippet.
See org.picketlink.identity.federation.bindings.jboss.auth.SAMLTokenCertValidatingCommonLoginModule
class of the picketlink-jbas-common source for implementation of methods getX509Certificate, validateCertPath used in the custom handler.
public class CustomSAML2Handler<C extends LogicalMessageContext> implements SOAPHandler {
protected boolean handleInbound(MessageContext msgContext) {
logger.info("Handling Inbound Message");
String assertionNS = JBossSAMLURIConstants.ASSERTION_NSURI.get();
SOAPMessageContext ctx = (SOAPMessageContext) msgContext;
SOAPMessage soapMessage = ctx.getMessage();
if (soapMessage == null)
throw logger.nullValueError("SOAP Message");
// retrieve the assertion
Document document = soapMessage.getSOAPPart();
Element soapHeader = Util.findOrCreateSoapHeader(document.getDocumentElement());
Element assertion = Util.findElement(soapHeader, new QName(assertionNS, "Assertion"));
if (assertion != null) {
AssertionType assertionType = null;
try {
assertionType = SAMLUtil.fromElement(assertion);
if (AssertionUtil.hasExpired(assertionType))
throw new RuntimeException(logger.samlAssertionExpiredError());
} catch (Exception e) {
logger.samlAssertionPasingFailed(e);
}
SamlCredential credential = new SamlCredential(assertion);
if (logger.isTraceEnabled()) {
logger.trace("Assertion included in SOAP payload: " + credential.getAssertionAsString());
}
try {
validateSAMLCredential(credential, assertionType);
ctx.put("roles",AssertionUtil.getRoles(assertionType, null));
ctx.setScope("roles", MessageContext.Scope.APPLICATION);
} catch (Exception e) {
logger.error("Error: " + e);
throw new RuntimeException(e);
}
} else {
logger.trace("We did not find any assertion");
}
return true;
}
private void validateSAMLCredential(SamlCredential credential, AssertionType assertion) throws LoginException, ConfigurationException, CertificateExpiredException, CertificateNotYetValidException {
// initialize xmlsec
org.apache.xml.security.Init.init();
X509Certificate cert = getX509Certificate(credential);
// public certificate validation
validateCertPath(cert);
// check time validity of the certificate
cert.checkValidity();
boolean sigValid = false;
try {
sigValid = AssertionUtil.isSignatureValid(credential.getAssertionAsElement(), cert.getPublicKey());
} catch (ProcessingException e) {
logger.processingError(e);
}
if (!sigValid) {
throw logger.authSAMLInvalidSignatureError();
}
if (AssertionUtil.hasExpired(assertion)) {
throw logger.authSAMLAssertionExpiredError();
}
}
}

Possible to access remote EJBs from a custom LoginModule?

I found some nice hints on how to write a custom realm and loginModule. I'm wondering though if it is possible to access a remote EJB within the custom loginModule.
In my case, I have remote EJBs that provide access to user-entities (via JPA) -- can I use them (e.g. via #EJB annotation)?
Ok, I found the answer myself: works fine! I can get a reference to the remote SLSB via an InitialContext.
Here's the code:
public class UserLoginModule extends AppservPasswordLoginModule {
Logger log = Logger.getLogger(this.getClass().getName());
private UserFacadeLocal userFacade;
public UserLoginModule() {
try {
InitialContext ic = new InitialContext();
userFacade = (UserFacadeLocal) ic.lookup("java:global/MyAppServer/UserFacade!com.skalio.myapp.beans.UserFacadeLocal");
log.info("userFacade bean received");
} catch (NamingException ex) {
log.warning("Unable to get userFacade Bean!");
}
}
#Override
protected void authenticateUser() throws LoginException {
log.fine("Attempting to authenticate user '"+ _username +"', '"+ _password +"'");
User user;
// get the realm
UserRealm userRealm = (UserRealm) _currentRealm;
try {
user = userFacade.authenticate(_username, _password.trim());
userFacade.detach(user);
} catch (UnauthorizedException e) {
log.warning("Authentication failed: "+ e.getMessage());
throw new LoginException("UserLogin authentication failed!");
} catch (Exception e) {
throw new LoginException("UserLogin failed: "+ e.getMessage());
}
log.fine("Authentication successful for "+ user);
// get the groups the user is a member of
String[] grpList = userRealm.authorize(user);
if (grpList == null) {
throw new LoginException("User is not member of any groups");
}
// Add the logged in user to the subject's principals.
// This works, but unfortunately, I can't reach the user object
// afterwards again.
Set principals = _subject.getPrincipals();
principals.add(new UserPrincipalImpl(user));
this.commitUserAuthentication(grpList);
}
}
The trick is to separate the interfaces for the beans from the WAR. I bundle all interfaces and common entities in a separate OSGi module and deploy it with asadmin --type osgi. As a result, the custom UserLoginModule can classload them.

Does anybody know how to use the jndi just from foreign jndi factory of weblogic?

I have configured a foreign jndi factory to which a link was according!But I dont know how to use the foreign jndi in my own application!
could anybody do me a favor???
Pretty vague question, so pretty vague answer... Here is how to obtain a Context:
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,
"t3://localhost:7001");
try {
ctx = new InitialContext(ht);
// Use the context in your program
}
catch (NamingException e) {
// a failure occurred
} finally {
try {
ctx.close();
} catch (Exception e) {
// a failure occurred
}
}
You'll need wl-client.jar on the class path. More details in Programming WebLogic JNDI.
PS: I am not swallowing exceptions, the documentation sample does :)