use of javax.naming.AuthenticationException in project pulsar by yahoo.
the class AuthenticationProviderAthenz method authenticate.
@Override
public String authenticate(AuthenticationDataSource authData) throws AuthenticationException {
SocketAddress clientAddress;
String roleToken;
if (authData.hasDataFromPeer()) {
clientAddress = authData.getPeerAddress();
} else {
throw new AuthenticationException("Authentication data source does not have a client address");
}
if (authData.hasDataFromCommand()) {
roleToken = authData.getCommandData();
} else if (authData.hasDataFromHttp()) {
roleToken = authData.getHttpHeader(AuthZpeClient.ZPE_TOKEN_HDR);
} else {
throw new AuthenticationException("Authentication data source does not have a role token");
}
if (roleToken == null) {
throw new AuthenticationException("Athenz token is null, can't authenticate");
}
if (roleToken.isEmpty()) {
throw new AuthenticationException("Athenz RoleToken is empty, Server is Using Athenz Authentication");
}
if (log.isDebugEnabled()) {
log.debug("Athenz RoleToken : [{}] received from Client: {}", roleToken, clientAddress);
}
RoleToken token = new RoleToken(roleToken);
if (!domainNameList.contains(token.getDomain())) {
throw new AuthenticationException(String.format("Athenz RoleToken Domain mismatch, Expected: %s, Found: %s", domainNameList.toString(), token.getDomain()));
}
// Synchronize for non-thread safe static calls inside athenz library
synchronized (this) {
PublicKey ztsPublicKey = AuthZpeClient.getZtsPublicKey(token.getKeyId());
int allowedOffset = 0;
if (ztsPublicKey == null) {
throw new AuthenticationException("Unable to retrieve ZTS Public Key");
}
if (token.validate(ztsPublicKey, allowedOffset, null)) {
log.info("Athenz Role Token : {}, Authorized for Client: {}", roleToken, clientAddress);
return token.getPrincipal();
} else {
throw new AuthenticationException(String.format("Athenz Role Token Not Authorized from Client: %s", clientAddress));
}
}
}
use of javax.naming.AuthenticationException in project pulsar by yahoo.
the class ServerConnection method handleConnect.
/**
* handles connect request and sends {@code State.Connected} ack to client
*/
@Override
protected void handleConnect(CommandConnect connect) {
checkArgument(state == State.Start);
if (LOG.isDebugEnabled()) {
LOG.debug("Received CONNECT from {}", remoteAddress);
}
if (service.getConfiguration().isAuthenticationEnabled()) {
try {
String authMethod = "none";
if (connect.hasAuthMethodName()) {
authMethod = connect.getAuthMethodName();
} else if (connect.hasAuthMethod()) {
// Legacy client is passing enum
authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
}
String authData = connect.getAuthData().toStringUtf8();
ChannelHandler sslHandler = ctx.channel().pipeline().get(TLS_HANDLER);
SSLSession sslSession = null;
if (sslHandler != null) {
sslSession = ((SslHandler) sslHandler).engine().getSession();
}
authRole = service.getAuthenticationService().authenticate(new AuthenticationDataCommand(authData, remoteAddress, sslSession), authMethod);
LOG.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod, authRole);
} catch (AuthenticationException e) {
String msg = "Unable to authenticate";
LOG.warn("[{}] {}: {}", remoteAddress, msg, e.getMessage());
ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg));
close();
return;
}
}
ctx.writeAndFlush(Commands.newConnected(connect));
state = State.Connected;
remoteEndpointProtocolVersion = connect.getProtocolVersion();
}
use of javax.naming.AuthenticationException in project jdk8u_jdk by JetBrains.
the class LdapSasl method saslBind.
/**
* Performs SASL bind.
* Creates a SaslClient by using a default CallbackHandler
* that uses the Context.SECURITY_PRINCIPAL and Context.SECURITY_CREDENTIALS
* properties to satisfy the callbacks, and by using the
* SASL_AUTHZ_ID property as the authorization id. If the SASL_AUTHZ_ID
* property has not been set, Context.SECURITY_PRINCIPAL is used.
* If SASL_CALLBACK has been set, use that instead of the default
* CallbackHandler.
*<p>
* If bind is successful and the selected SASL mechanism has a security
* layer, set inStream and outStream to be filter streams that use
* the security layer. These will be used for subsequent communication
* with the server.
*<p>
* @param conn The non-null connection to use for sending an LDAP BIND
* @param server Non-null string name of host to connect to
* @param dn Non-null DN to bind as; also used as authentication ID
* @param pw Possibly null password; can be byte[], char[] or String
* @param authMech A non-null space-separated list of SASL authentication
* mechanisms.
* @param env The possibly null environment of the context, possibly containing
* properties for used by SASL mechanisms
* @param bindCtls The possibly null controls to accompany the bind
* @return LdapResult containing status of the bind
*/
@SuppressWarnings("unchecked")
public static LdapResult saslBind(LdapClient clnt, Connection conn, String server, String dn, Object pw, String authMech, Hashtable<?, ?> env, Control[] bindCtls) throws IOException, NamingException {
SaslClient saslClnt = null;
boolean cleanupHandler = false;
// Use supplied callback handler or create default
CallbackHandler cbh = (env != null) ? (CallbackHandler) env.get(SASL_CALLBACK) : null;
if (cbh == null) {
cbh = new DefaultCallbackHandler(dn, pw, (String) env.get(SASL_REALM));
cleanupHandler = true;
}
// Prepare parameters for creating SASL client
String authzId = (env != null) ? (String) env.get(SASL_AUTHZ_ID) : null;
String[] mechs = getSaslMechanismNames(authMech);
try {
// Create SASL client to use using SASL package
saslClnt = Sasl.createSaslClient(mechs, authzId, "ldap", server, (Hashtable<String, ?>) env, cbh);
if (saslClnt == null) {
throw new AuthenticationNotSupportedException(authMech);
}
LdapResult res;
String mechName = saslClnt.getMechanismName();
byte[] response = saslClnt.hasInitialResponse() ? saslClnt.evaluateChallenge(NO_BYTES) : null;
res = clnt.ldapBind(null, response, bindCtls, mechName, true);
while (!saslClnt.isComplete() && (res.status == LDAP_SASL_BIND_IN_PROGRESS || res.status == LDAP_SUCCESS)) {
response = saslClnt.evaluateChallenge(res.serverCreds != null ? res.serverCreds : NO_BYTES);
if (res.status == LDAP_SUCCESS) {
if (response != null) {
throw new AuthenticationException("SASL client generated response after success");
}
break;
}
res = clnt.ldapBind(null, response, bindCtls, mechName, true);
}
if (res.status == LDAP_SUCCESS) {
if (!saslClnt.isComplete()) {
throw new AuthenticationException("SASL authentication not complete despite server claims");
}
String qop = (String) saslClnt.getNegotiatedProperty(Sasl.QOP);
// If negotiated integrity or privacy,
if (qop != null && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf"))) {
InputStream newIn = new SaslInputStream(saslClnt, conn.inStream);
OutputStream newOut = new SaslOutputStream(saslClnt, conn.outStream);
conn.replaceStreams(newIn, newOut);
} else {
saslClnt.dispose();
}
}
return res;
} catch (SaslException e) {
NamingException ne = new AuthenticationException(authMech);
ne.setRootCause(e);
throw ne;
} finally {
if (cleanupHandler) {
((DefaultCallbackHandler) cbh).clearPassword();
}
}
}
use of javax.naming.AuthenticationException in project adempiere by adempiere.
the class LDAP method validate.
/**
* Validate User
* @param ldapURL provider url - e.g. ldap://dc.compiere.org
* @param domain domain name = e.g. compiere.org
* @param userName user name - e.g. jjanke
* @param password password
* @return true if validated with ldap
*/
public static boolean validate(String ldapURL, String domain, String userName, String password) {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
// ldap://dc.compiere.org
env.put(Context.PROVIDER_URL, ldapURL);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
// jjanke@compiere.org
// For OpenLDAP uncomment the next line
// StringBuffer principal = new StringBuffer("uid=").append(userName).append(",").append(domain);
StringBuffer principal = new StringBuffer(userName).append("@").append(domain);
env.put(Context.SECURITY_PRINCIPAL, principal.toString());
env.put(Context.SECURITY_CREDENTIALS, password);
//
try {
// Create the initial context
InitialLdapContext ctx = new InitialLdapContext(env, null);
// DirContext ctx = new InitialDirContext(env);
// Test - Get the attributes
Attributes answer = ctx.getAttributes("");
// Print the answer
if (false)
dump(answer);
} catch (AuthenticationException e) {
log.info("Error: " + principal + " - " + e.getLocalizedMessage());
return false;
} catch (Exception e) {
log.log(Level.SEVERE, ldapURL + " - " + principal, e);
return false;
}
log.info("OK: " + principal);
return true;
}
use of javax.naming.AuthenticationException in project tomee by apache.
the class ContractTest method invalid.
@Test
public void invalid() throws NamingException {
try {
hi(new Properties() {
{
setProperty(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
setProperty(Context.PROVIDER_URL, String.format("http://localhost:%s/tomee/ejb", base.getPort()));
setProperty(Context.SECURITY_PRINCIPAL, "tomcat");
setProperty(Context.SECURITY_CREDENTIALS, "wrong");
}
});
fail();
} catch (final AuthenticationException ae) {
// ok
}
}
Aggregations