Java Examples for javax.security.sasl.SaslClientFactory
The following java examples will help you to understand the usage of javax.security.sasl.SaslClientFactory. These source code samples are taken from different open source projects.
Example 1
Project: openamq-jms-master File: DynamicSaslRegistrar.java View source code |
public static void registerSaslProviders() {
InputStream is = openPropertiesInputStream();
try {
Properties props = new Properties();
props.load(is);
Map<String, Class<? extends SaslClientFactory>> factories = parseProperties(props);
if (factories.size() > 0) {
Security.addProvider(new JCAProvider(factories));
_logger.debug("Dynamic SASL provider added as a security provider");
}
} catch (IOException e) {
_logger.error("Error reading properties: " + e, e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
_logger.error("Unable to close properties stream: " + e, e);
}
}
}
}
Example 2
Project: wildfly-elytron-master File: AuthenticationConfiguration.java View source code |
SaslClient createSaslClient(URI uri, Collection<String> serverMechanisms, UnaryOperator<SaslClientFactory> factoryOperator, SSLSession sslSession) throws SaslException { SaslClientFactory saslClientFactory = factoryOperator.apply(getSaslClientFactory()); final SaslMechanismSelector selector = this.saslMechanismSelector; serverMechanisms = (selector == null ? SaslMechanismSelector.DEFAULT : selector).apply(serverMechanisms, sslSession); if (serverMechanisms.isEmpty()) { return null; } final Principal authorizationPrincipal = getAuthorizationPrincipal(); final Predicate<String> filter; final String authzName; if (authorizationPrincipal == null) { filter = this::saslSupportedByConfiguration; authzName = null; } else if (authorizationPrincipal instanceof NamePrincipal) { filter = this::saslSupportedByConfiguration; authzName = authorizationPrincipal.getName(); } else if (authorizationPrincipal instanceof AnonymousPrincipal) { filter = ((Predicate<String>) this::saslSupportedByConfiguration).and("ANONYMOUS"::equals); authzName = null; } else { return null; } Map<String, ?> mechanismProperties = this.mechanismProperties; if (!mechanismProperties.isEmpty()) { mechanismProperties = new HashMap<>(mechanismProperties); // special handling for JBOSS-LOCAL-USER quiet auth... only pass it through if we have a user callback if (!userCallbackKinds.contains(CallbackKind.PRINCIPAL)) { mechanismProperties.remove(LocalUserClient.QUIET_AUTH); mechanismProperties.remove(LocalUserClient.LEGACY_QUIET_AUTH); } if (!mechanismProperties.isEmpty()) { saslClientFactory = new PropertiesSaslClientFactory(saslClientFactory, mechanismProperties); } } String host = getHost(); if (host != null) { saslClientFactory = new ServerNameSaslClientFactory(saslClientFactory, host); } String protocol = getProtocol(); if (protocol != null) { saslClientFactory = new ProtocolSaslClientFactory(saslClientFactory, protocol); } saslClientFactory = new LocalPrincipalSaslClientFactory(new FilterMechanismSaslClientFactory(saslClientFactory, filter)); return saslClientFactory.createSaslClient(serverMechanisms.toArray(NO_STRINGS), authzName, uri.getScheme(), uri.getHost(), Collections.emptyMap(), createCallbackHandler()); }
Example 3
Project: drill-master File: FastSaslClientFactory.java View source code |
// used in initialization, and for testing private void refresh() { final Enumeration<SaslClientFactory> factories = Sasl.getSaslClientFactories(); final Map<String, List<SaslClientFactory>> map = Maps.newHashMap(); while (factories.hasMoreElements()) { final SaslClientFactory factory = factories.nextElement(); // instantiating a client are what really matter. See createSaslClient. for (final String mechanismName : factory.getMechanismNames(null)) { if (!map.containsKey(mechanismName)) { map.put(mechanismName, new ArrayList<SaslClientFactory>()); } map.get(mechanismName).add(factory); } } clientFactories = ImmutableMap.copyOf(map); if (logger.isDebugEnabled()) { logger.debug("Registered sasl client factories: {}", clientFactories.keySet()); } }
Example 4
Project: JGroups-master File: SaslUtils.java View source code |
public static SaslClientFactory getSaslClientFactory(String mech, Map<String, ?> props) { Iterator<SaslClientFactory> saslFactories = SaslUtils.getSaslClientFactories(SaslUtils.class.getClassLoader(), true); while (saslFactories.hasNext()) { SaslClientFactory saslFactory = saslFactories.next(); for (String supportedMech : saslFactory.getMechanismNames(props)) { if (mech.equals(supportedMech)) { return saslFactory; } } } throw new IllegalArgumentException("No SASL client factory for mech " + mech); }
Example 5
Project: jboss-remoting-master File: EndpointImpl.java View source code |
IoFuture<Connection> connect(final URI destination, final SocketAddress bindAddress, final OptionMap connectOptions, final AuthenticationConfiguration configuration, final UnaryOperator<SaslClientFactory> saslClientFactoryOperator, final SSLContext sslContext) { Assert.checkNotNullParam("destination", destination); Assert.checkNotNullParam("connectOptions", connectOptions); final String protocol = connectOptions.contains(RemotingOptions.SASL_PROTOCOL) ? connectOptions.get(RemotingOptions.SASL_PROTOCOL) : RemotingOptions.DEFAULT_SASL_PROTOCOL; UnaryOperator<SaslClientFactory> factoryOperator = PrivilegedSaslClientFactory::new; factoryOperator = and(factoryOperator, factory -> new ProtocolSaslClientFactory(factory, protocol)); if (connectOptions.contains(RemotingOptions.SERVER_NAME)) { final String serverName = connectOptions.get(RemotingOptions.SERVER_NAME); factoryOperator = and(factoryOperator, factory -> new ServerNameSaslClientFactory(factory, serverName)); } factoryOperator = and(factoryOperator, saslClientFactoryOperator); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(RemotingPermission.CONNECT); } final String scheme = destination.getScheme(); synchronized (connectionLock) { boolean ok = false; try { resourceUntick("Connection to " + destination); } catch (NotOpenException e) { return new FailedIoFuture<>(e); } try { final ProtocolRegistration protocolRegistration = connectionProviders.get(scheme); if (protocolRegistration == null) { return new FailedIoFuture<>(new UnknownURISchemeException("No connection provider for URI scheme \"" + scheme + "\" is installed")); } final ConnectionProvider connectionProvider = protocolRegistration.getProvider(); final FutureResult<Connection> futureResult = new FutureResult<Connection>(getExecutor()); // Mark the stack because otherwise debugging connect problems can be incredibly tough final StackTraceElement[] mark = Thread.currentThread().getStackTrace(); final UnaryOperator<SaslClientFactory> finalFactoryOperator = factoryOperator; final Result<ConnectionHandlerFactory> result = new Result<ConnectionHandlerFactory>() { private final AtomicBoolean flag = new AtomicBoolean(); public boolean setCancelled() { if (!flag.compareAndSet(false, true)) { return false; } log.logf(getClass().getName(), Logger.Level.TRACE, null, "Registered cancellation result"); closeTick1("a cancelled connection"); futureResult.setCancelled(); return true; } public boolean setException(final IOException exception) { if (!flag.compareAndSet(false, true)) { return false; } log.logf(getClass().getName(), Logger.Level.TRACE, exception, "Registered exception result"); closeTick1("a failed connection (2)"); SpiUtils.glueStackTraces(exception, mark, 1, "asynchronous invocation"); futureResult.setException(exception); return true; } public boolean setResult(final ConnectionHandlerFactory connHandlerFactory) { if (!flag.compareAndSet(false, true)) { return false; } synchronized (connectionLock) { log.logf(getClass().getName(), Logger.Level.TRACE, null, "Registered successful result %s", connHandlerFactory); final ConnectionImpl connection = new ConnectionImpl(EndpointImpl.this, connHandlerFactory, protocolRegistration.getContext(), destination, null, configuration, protocol); connections.add(connection); connection.getConnectionHandler().addCloseHandler(SpiUtils.asyncClosingCloseHandler(connection)); connection.addCloseHandler(resourceCloseHandler); connection.addCloseHandler(connectionCloseHandler); // see if we were closed in the meantime if (EndpointImpl.this.isCloseFlagSet()) { connection.closeAsync(); futureResult.setCancelled(); } else { futureResult.setResult(connection); } } return true; } }; final Cancellable connect = doPrivileged((PrivilegedAction<Cancellable>) () -> connectionProvider.connect(destination, bindAddress, connectOptions, result, configuration, sslContext, finalFactoryOperator, Collections.emptyList())); ok = true; futureResult.addCancelHandler(connect); return futureResult.getIoFuture(); } finally { if (!ok) { closeTick1("a failed connection (1)"); } } } }
Example 6
Project: kolmafia-master File: SVNSaslAuthenticator.java View source code |
protected SaslClient createSaslClient(List mechs, String realm, SVNRepositoryImpl repos, SVNURL location) throws SVNException {
Map props = new SVNHashMap();
props.put(Sasl.QOP, "auth-conf,auth-int,auth");
props.put(Sasl.MAX_BUFFER, "8192");
props.put(Sasl.RAW_SEND_SIZE, "8192");
props.put(Sasl.POLICY_NOPLAINTEXT, "false");
props.put(Sasl.REUSE, "false");
props.put(Sasl.POLICY_NOANONYMOUS, "true");
String[] mechsArray = (String[]) mechs.toArray(new String[mechs.size()]);
SaslClient client = null;
for (int i = 0; i < mechsArray.length; i++) {
String mech = mechsArray[i];
try {
if ("ANONYMOUS".equals(mech) || "EXTERNAL".equals(mech) || "PLAIN".equals(mech)) {
props.put(Sasl.POLICY_NOANONYMOUS, "false");
}
SaslClientFactory clientFactory = getSaslClientFactory(mech, props);
if (clientFactory == null) {
continue;
}
SVNAuthentication auth = null;
if ("ANONYMOUS".equals(mech)) {
auth = SVNPasswordAuthentication.newInstance("", new char[0], false, location, false);
} else if ("EXTERNAL".equals(mech)) {
String name = repos.getExternalUserName();
if (name == null) {
name = "";
}
auth = SVNPasswordAuthentication.newInstance(name, new char[0], false, location, false);
} else {
if (myAuthenticationManager == null) {
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Authentication required for ''{0}''", realm), SVNLogType.NETWORK);
}
String realmName = getFullRealmName(location, realm);
if (myAuthentication != null) {
myAuthentication = myAuthenticationManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realmName, location);
} else {
myAuthentication = myAuthenticationManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realmName, location);
}
if (myAuthentication == null) {
if (getLastError() != null) {
SVNErrorManager.error(getLastError(), SVNLogType.NETWORK);
}
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "Authentication required for ''{0}''", realm), SVNLogType.NETWORK);
}
auth = myAuthentication;
}
client = clientFactory.createSaslClient(new String[] { "ANONYMOUS".equals(mech) ? "PLAIN" : mech }, null, "svn", location.getHost(), props, new SVNCallbackHandler(realm, auth));
if (client != null) {
break;
}
myAuthentication = null;
} catch (SaslException e) {
mechs.remove(mechsArray[i]);
myAuthentication = null;
}
}
return client;
}
Example 7
Project: pwm-master File: NMASCrOperator.java View source code |
public Object run() {
try {
final String saslFactoryName = password.pwm.util.operations.cr.NMASCrOperator.NMASCrPwmSaslFactory.class.getName();
thisInstance.put("SaslClientFactory." + SASL_PROVIDER_NAME, saslFactoryName);
} catch (SecurityException e) {
LOGGER.warn("error registering " + NMASCrPwmSaslProvider.class.getSimpleName() + " SASL Provider, error: " + e.getMessage(), e);
}
return null;
}
Example 8
Project: ikvm-openjdk-master File: Sasl.java View source code |
/** * Creates a <tt>SaslClient</tt> using the parameters supplied. * * This method uses the <a href="{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html#Provider">JCA Security Provider Framework</a>, described in the * "Java Cryptography Architecture API Specification & Reference", for * locating and selecting a <tt>SaslClient</tt> implementation. * * First, it * obtains an ordered list of <tt>SaslClientFactory</tt> instances from * the registered security providers for the "SaslClientFactory" service * and the specified SASL mechanism(s). It then invokes * <tt>createSaslClient()</tt> on each factory instance on the list * until one produces a non-null <tt>SaslClient</tt> instance. It returns * the non-null <tt>SaslClient</tt> instance, or null if the search fails * to produce a non-null <tt>SaslClient</tt> instance. *<p> * A security provider for SaslClientFactory registers with the * JCA Security Provider Framework keys of the form <br> * <tt>SaslClientFactory.<em>mechanism_name</em></tt> * <br> * and values that are class names of implementations of * <tt>javax.security.sasl.SaslClientFactory</tt>. * * For example, a provider that contains a factory class, * <tt>com.wiz.sasl.digest.ClientFactory</tt>, that supports the * "DIGEST-MD5" mechanism would register the following entry with the JCA: * <tt>SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory</tt> *<p> * See the * "Java Cryptography Architecture API Specification & Reference" * for information about how to install and configure security service * providers. * * @param mechanisms The non-null list of mechanism names to try. Each is the * IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5"). * @param authorizationId The possibly null protocol-dependent * identification to be used for authorization. * If null or empty, the server derives an authorization * ID from the client's authentication credentials. * When the SASL authentication completes successfully, * the specified entity is granted access. * * @param protocol The non-null string name of the protocol for which * the authentication is being performed (e.g., "ldap"). * * @param serverName The non-null fully-qualified host name of the server * to authenticate to. * * @param props The possibly null set of properties used to * select the SASL mechanism and to configure the authentication * exchange of the selected mechanism. * For example, if <tt>props</tt> contains the * <code>Sasl.POLICY_NOPLAINTEXT</code> property with the value * <tt>"true"</tt>, then the selected * SASL mechanism must not be susceptible to simple plain passive attacks. * In addition to the standard properties declared in this class, * other, possibly mechanism-specific, properties can be included. * Properties not relevant to the selected mechanism are ignored, * including any map entries with non-String keys. * * @param cbh The possibly null callback handler to used by the SASL * mechanisms to get further information from the application/library * to complete the authentication. For example, a SASL mechanism might * require the authentication ID, password and realm from the caller. * The authentication ID is requested by using a <tt>NameCallback</tt>. * The password is requested by using a <tt>PasswordCallback</tt>. * The realm is requested by using a <tt>RealmChoiceCallback</tt> if there is a list * of realms to choose from, and by using a <tt>RealmCallback</tt> if * the realm must be entered. * *@return A possibly null <tt>SaslClient</tt> created using the parameters * supplied. If null, cannot find a <tt>SaslClientFactory</tt> * that will produce one. *@exception SaslException If cannot create a <tt>SaslClient</tt> because * of an error. */ public static SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { SaslClient mech = null; SaslClientFactory fac; String className; String mechName; for (int i = 0; i < mechanisms.length; i++) { if ((mechName = mechanisms[i]) == null) { throw new NullPointerException("Mechanism name cannot be null"); } else if (mechName.length() == 0) { continue; } String mechFilter = "SaslClientFactory." + mechName; Provider[] provs = Security.getProviders(mechFilter); for (int j = 0; provs != null && j < provs.length; j++) { className = provs[j].getProperty(mechFilter); if (className == null) { // Case is ignored continue; } fac = (SaslClientFactory) loadFactory(provs[j], className); if (fac != null) { mech = fac.createSaslClient(new String[] { mechanisms[i] }, authorizationId, protocol, serverName, props, cbh); if (mech != null) { return mech; } } } } return null; }