List of usage examples for javax.naming Context SECURITY_PROTOCOL
String SECURITY_PROTOCOL
To view the source code for javax.naming Context SECURITY_PROTOCOL.
Click Source Link
From source file:org.apache.hadoop.security.LdapGroupsMapping.java
DirContext getDirContext() throws NamingException { if (ctx == null) { // Set up the initial environment for LDAP connectivity Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.ldap.LdapCtxFactory.class.getName()); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); // Set up SSL security, if necessary if (useSsl) { env.put(Context.SECURITY_PROTOCOL, "ssl"); System.setProperty("javax.net.ssl.keyStore", keystore); System.setProperty("javax.net.ssl.keyStorePassword", keystorePass); }/*from w w w .j av a 2 s.c om*/ env.put(Context.SECURITY_PRINCIPAL, bindUser); env.put(Context.SECURITY_CREDENTIALS, bindPassword); env.put("com.sun.jndi.ldap.connect.timeout", conf.get(CONNECTION_TIMEOUT, String.valueOf(CONNECTION_TIMEOUT_DEFAULT))); env.put("com.sun.jndi.ldap.read.timeout", conf.get(READ_TIMEOUT, String.valueOf(READ_TIMEOUT_DEFAULT))); ctx = new InitialDirContext(env); } return ctx; }
From source file:org.apache.nifi.ldap.LdapProvider.java
@Override public final void onConfigured(final LoginIdentityProviderConfigurationContext configurationContext) throws ProviderCreationException { final String rawExpiration = configurationContext.getProperty("Authentication Expiration"); if (StringUtils.isBlank(rawExpiration)) { throw new ProviderCreationException("The Authentication Expiration must be specified."); }//from ww w . j a va2s. c om try { expiration = FormatUtils.getTimeDuration(rawExpiration, TimeUnit.MILLISECONDS); } catch (final IllegalArgumentException iae) { throw new ProviderCreationException( String.format("The Expiration Duration '%s' is not a valid time duration", rawExpiration)); } final LdapContextSource context = new LdapContextSource(); final Map<String, Object> baseEnvironment = new HashMap<>(); // connect/read time out setTimeout(configurationContext, baseEnvironment, "Connect Timeout", "com.sun.jndi.ldap.connect.timeout"); setTimeout(configurationContext, baseEnvironment, "Read Timeout", "com.sun.jndi.ldap.read.timeout"); // authentication strategy final String rawAuthenticationStrategy = configurationContext.getProperty("Authentication Strategy"); final LdapAuthenticationStrategy authenticationStrategy; try { authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy); } catch (final IllegalArgumentException iae) { throw new ProviderCreationException(String.format( "Unrecognized authentication strategy '%s'. Possible values are [%s]", rawAuthenticationStrategy, StringUtils.join(LdapAuthenticationStrategy.values(), ", "))); } switch (authenticationStrategy) { case ANONYMOUS: context.setAnonymousReadOnly(true); break; default: final String userDn = configurationContext.getProperty("Manager DN"); final String password = configurationContext.getProperty("Manager Password"); context.setUserDn(userDn); context.setPassword(password); switch (authenticationStrategy) { case SIMPLE: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); break; case LDAPS: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); // indicate a secure connection baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); // get the configured ssl context final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext); if (ldapsSslContext != null) { // initialize the ldaps socket factory prior to use LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory()); baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName()); } break; case START_TLS: final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); // shutdown gracefully final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully"); if (StringUtils.isNotBlank(rawShutdownGracefully)) { final boolean shutdownGracefully = Boolean.TRUE.toString() .equalsIgnoreCase(rawShutdownGracefully); tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully); } // get the configured ssl context final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext); if (startTlsSslContext != null) { tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory()); } // set the authentication strategy context.setAuthenticationStrategy(tlsAuthenticationStrategy); break; } break; } // referrals final String rawReferralStrategy = configurationContext.getProperty("Referral Strategy"); final ReferralStrategy referralStrategy; try { referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy); } catch (final IllegalArgumentException iae) { throw new ProviderCreationException( String.format("Unrecognized referral strategy '%s'. Possible values are [%s]", rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", "))); } // using the value as this needs to be the lowercase version while the value is configured with the enum constant context.setReferral(referralStrategy.getValue()); // url final String urls = configurationContext.getProperty("Url"); if (StringUtils.isBlank(urls)) { throw new ProviderCreationException("LDAP identity provider 'Url' must be specified."); } // connection context.setUrls(StringUtils.split(urls)); // search criteria final String userSearchBase = configurationContext.getProperty("User Search Base"); final String userSearchFilter = configurationContext.getProperty("User Search Filter"); if (StringUtils.isBlank(userSearchBase) || StringUtils.isBlank(userSearchFilter)) { throw new ProviderCreationException( "LDAP identity provider 'User Search Base' and 'User Search Filter' must be specified."); } final LdapUserSearch userSearch = new FilterBasedLdapUserSearch(userSearchBase, userSearchFilter, context); // bind final BindAuthenticator authenticator = new BindAuthenticator(context); authenticator.setUserSearch(userSearch); // identity strategy final String rawIdentityStrategy = configurationContext.getProperty("Identity Strategy"); if (StringUtils.isBlank(rawIdentityStrategy)) { logger.info(String.format("Identity Strategy is not configured, defaulting strategy to %s.", IdentityStrategy.USE_DN)); // if this value is not configured, default to use dn which was the previous implementation identityStrategy = IdentityStrategy.USE_DN; } else { try { // attempt to get the configured identity strategy identityStrategy = IdentityStrategy.valueOf(rawIdentityStrategy); } catch (final IllegalArgumentException iae) { throw new ProviderCreationException( String.format("Unrecognized identity strategy '%s'. Possible values are [%s]", rawIdentityStrategy, StringUtils.join(IdentityStrategy.values(), ", "))); } } // set the base environment is necessary if (!baseEnvironment.isEmpty()) { context.setBaseEnvironmentProperties(baseEnvironment); } try { // handling initializing beans context.afterPropertiesSet(); authenticator.afterPropertiesSet(); } catch (final Exception e) { throw new ProviderCreationException(e.getMessage(), e); } // create the underlying provider provider = new LdapAuthenticationProvider(authenticator); }
From source file:org.apache.nifi.ldap.tenants.LdapUserGroupProvider.java
@Override public void onConfigured(final AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException { final LdapContextSource context = new LdapContextSource(); final Map<String, Object> baseEnvironment = new HashMap<>(); // connect/read time out setTimeout(configurationContext, baseEnvironment, PROP_CONNECT_TIMEOUT, "com.sun.jndi.ldap.connect.timeout"); setTimeout(configurationContext, baseEnvironment, PROP_READ_TIMEOUT, "com.sun.jndi.ldap.read.timeout"); // authentication strategy final PropertyValue rawAuthenticationStrategy = configurationContext .getProperty(PROP_AUTHENTICATION_STRATEGY); final LdapAuthenticationStrategy authenticationStrategy; try {/*from ww w. java 2 s . c o m*/ authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy.getValue()); } catch (final IllegalArgumentException iae) { throw new AuthorizerCreationException( String.format("Unrecognized authentication strategy '%s'. Possible values are [%s]", rawAuthenticationStrategy.getValue(), StringUtils.join(LdapAuthenticationStrategy.values(), ", "))); } switch (authenticationStrategy) { case ANONYMOUS: context.setAnonymousReadOnly(true); break; default: final String userDn = configurationContext.getProperty(PROP_MANAGER_DN).getValue(); final String password = configurationContext.getProperty(PROP_MANAGER_PASSWORD).getValue(); context.setUserDn(userDn); context.setPassword(password); switch (authenticationStrategy) { case SIMPLE: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); break; case LDAPS: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); // indicate a secure connection baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); // get the configured ssl context final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext); if (ldapsSslContext != null) { // initialize the ldaps socket factory prior to use LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory()); baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName()); } break; case START_TLS: final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); // shutdown gracefully final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully") .getValue(); if (StringUtils.isNotBlank(rawShutdownGracefully)) { final boolean shutdownGracefully = Boolean.TRUE.toString() .equalsIgnoreCase(rawShutdownGracefully); tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully); } // get the configured ssl context final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext); if (startTlsSslContext != null) { tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory()); } // set the authentication strategy context.setAuthenticationStrategy(tlsAuthenticationStrategy); break; } break; } // referrals final String rawReferralStrategy = configurationContext.getProperty(PROP_REFERRAL_STRATEGY).getValue(); final ReferralStrategy referralStrategy; try { referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy); } catch (final IllegalArgumentException iae) { throw new AuthorizerCreationException( String.format("Unrecognized referral strategy '%s'. Possible values are [%s]", rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", "))); } // using the value as this needs to be the lowercase version while the value is configured with the enum constant context.setReferral(referralStrategy.getValue()); // url final String urls = configurationContext.getProperty(PROP_URL).getValue(); if (StringUtils.isBlank(urls)) { throw new AuthorizerCreationException("LDAP identity provider 'Url' must be specified."); } // connection context.setUrls(StringUtils.split(urls)); // raw user search base final PropertyValue rawUserSearchBase = configurationContext.getProperty(PROP_USER_SEARCH_BASE); final PropertyValue rawUserObjectClass = configurationContext.getProperty(PROP_USER_OBJECT_CLASS); final PropertyValue rawUserSearchScope = configurationContext.getProperty(PROP_USER_SEARCH_SCOPE); // if loading the users, ensure the object class set if (rawUserSearchBase.isSet() && !rawUserObjectClass.isSet()) { throw new AuthorizerCreationException( "LDAP user group provider 'User Object Class' must be specified when 'User Search Base' is set."); } // if loading the users, ensure the search scope is set if (rawUserSearchBase.isSet() && !rawUserSearchScope.isSet()) { throw new AuthorizerCreationException( "LDAP user group provider 'User Search Scope' must be specified when 'User Search Base' is set."); } // user search criteria userSearchBase = rawUserSearchBase.getValue(); userObjectClass = rawUserObjectClass.getValue(); userSearchFilter = configurationContext.getProperty(PROP_USER_SEARCH_FILTER).getValue(); userIdentityAttribute = configurationContext.getProperty(PROP_USER_IDENTITY_ATTRIBUTE).getValue(); userGroupNameAttribute = configurationContext.getProperty(PROP_USER_GROUP_ATTRIBUTE).getValue(); userGroupReferencedGroupAttribute = configurationContext .getProperty(PROP_USER_GROUP_REFERENCED_GROUP_ATTRIBUTE).getValue(); try { userSearchScope = SearchScope.valueOf(rawUserSearchScope.getValue()); } catch (final IllegalArgumentException iae) { throw new AuthorizerCreationException( String.format("Unrecognized user search scope '%s'. Possible values are [%s]", rawUserSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", "))); } // determine user behavior useDnForUserIdentity = StringUtils.isBlank(userIdentityAttribute); performUserSearch = StringUtils.isNotBlank(userSearchBase); // raw group search criteria final PropertyValue rawGroupSearchBase = configurationContext.getProperty(PROP_GROUP_SEARCH_BASE); final PropertyValue rawGroupObjectClass = configurationContext.getProperty(PROP_GROUP_OBJECT_CLASS); final PropertyValue rawGroupSearchScope = configurationContext.getProperty(PROP_GROUP_SEARCH_SCOPE); // if loading the groups, ensure the object class is set if (rawGroupSearchBase.isSet() && !rawGroupObjectClass.isSet()) { throw new AuthorizerCreationException( "LDAP user group provider 'Group Object Class' must be specified when 'Group Search Base' is set."); } // if loading the groups, ensure the search scope is set if (rawGroupSearchBase.isSet() && !rawGroupSearchScope.isSet()) { throw new AuthorizerCreationException( "LDAP user group provider 'Group Search Scope' must be specified when 'Group Search Base' is set."); } // group search criteria groupSearchBase = rawGroupSearchBase.getValue(); groupObjectClass = rawGroupObjectClass.getValue(); groupSearchFilter = configurationContext.getProperty(PROP_GROUP_SEARCH_FILTER).getValue(); groupNameAttribute = configurationContext.getProperty(PROP_GROUP_NAME_ATTRIBUTE).getValue(); groupMemberAttribute = configurationContext.getProperty(PROP_GROUP_MEMBER_ATTRIBUTE).getValue(); groupMemberReferencedUserAttribute = configurationContext .getProperty(PROP_GROUP_MEMBER_REFERENCED_USER_ATTRIBUTE).getValue(); try { groupSearchScope = SearchScope.valueOf(rawGroupSearchScope.getValue()); } catch (final IllegalArgumentException iae) { throw new AuthorizerCreationException( String.format("Unrecognized group search scope '%s'. Possible values are [%s]", rawGroupSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", "))); } // determine group behavior useDnForGroupName = StringUtils.isBlank(groupNameAttribute); performGroupSearch = StringUtils.isNotBlank(groupSearchBase); // ensure we are either searching users or groups (at least one must be specified) if (!performUserSearch && !performGroupSearch) { throw new AuthorizerCreationException( "LDAP user group provider 'User Search Base' or 'Group Search Base' must be specified."); } // ensure group member attribute is set if searching groups but not users if (performGroupSearch && !performUserSearch && StringUtils.isBlank(groupMemberAttribute)) { throw new AuthorizerCreationException( "'Group Member Attribute' is required when searching groups but not users."); } // ensure that performUserSearch is set when groupMemberReferencedUserAttribute is specified if (StringUtils.isNotBlank(groupMemberReferencedUserAttribute) && !performUserSearch) { throw new AuthorizerCreationException( "''User Search Base' must be set when specifying 'Group Member Attribute - Referenced User Attribute'."); } // ensure that performGroupSearch is set when userGroupReferencedGroupAttribute is specified if (StringUtils.isNotBlank(userGroupReferencedGroupAttribute) && !performGroupSearch) { throw new AuthorizerCreationException( "'Group Search Base' must be set when specifying 'User Group Name Attribute - Referenced Group Attribute'."); } // get the page size if configured final PropertyValue rawPageSize = configurationContext.getProperty(PROP_PAGE_SIZE); if (rawPageSize.isSet() && StringUtils.isNotBlank(rawPageSize.getValue())) { pageSize = rawPageSize.asInteger(); } // extract the identity mappings from nifi.properties if any are provided identityMappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties)); // set the base environment is necessary if (!baseEnvironment.isEmpty()) { context.setBaseEnvironmentProperties(baseEnvironment); } try { // handling initializing beans context.afterPropertiesSet(); } catch (final Exception e) { throw new AuthorizerCreationException(e.getMessage(), e); } final PropertyValue rawSyncInterval = configurationContext.getProperty(PROP_SYNC_INTERVAL); final long syncInterval; if (rawSyncInterval.isSet()) { try { syncInterval = FormatUtils.getTimeDuration(rawSyncInterval.getValue(), TimeUnit.MILLISECONDS); } catch (final IllegalArgumentException iae) { throw new AuthorizerCreationException(String.format("The %s '%s' is not a valid time duration", PROP_SYNC_INTERVAL, rawSyncInterval.getValue())); } if (syncInterval < MINIMUM_SYNC_INTERVAL_MILLISECONDS) { throw new AuthorizerCreationException( String.format("The %s '%s' is below the minimum value of '%d ms'", PROP_SYNC_INTERVAL, rawSyncInterval.getValue(), MINIMUM_SYNC_INTERVAL_MILLISECONDS)); } } else { throw new AuthorizerCreationException(String.format("The '%s' must be specified.", PROP_SYNC_INTERVAL)); } try { // perform the initial load, tenants must be loaded as the configured UserGroupProvider is supplied // to the AccessPolicyProvider for granting initial permissions load(context); // ensure the tenants were successfully synced if (tenants.get() == null) { throw new AuthorizerCreationException("Unable to sync users and groups."); } // schedule the background thread to load the users/groups ldapSync.scheduleWithFixedDelay(() -> load(context), syncInterval, syncInterval, TimeUnit.MILLISECONDS); } catch (final AuthorizationAccessException e) { throw new AuthorizerCreationException(e); } }
From source file:org.apache.nifi.registry.security.ldap.LdapIdentityProvider.java
@Override public final void onConfigured(final IdentityProviderConfigurationContext configurationContext) throws SecurityProviderCreationException { final String rawExpiration = configurationContext.getProperty("Authentication Expiration"); if (StringUtils.isBlank(rawExpiration)) { throw new SecurityProviderCreationException("The Authentication Expiration must be specified."); }/*from w w w . j a v a 2 s .c om*/ try { expiration = FormatUtils.getTimeDuration(rawExpiration, TimeUnit.MILLISECONDS); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("The Expiration Duration '%s' is not a valid time duration", rawExpiration)); } final LdapContextSource context = new LdapContextSource(); final Map<String, Object> baseEnvironment = new HashMap<>(); // connect/read time out setTimeout(configurationContext, baseEnvironment, "Connect Timeout", "com.sun.jndi.ldap.connect.timeout"); setTimeout(configurationContext, baseEnvironment, "Read Timeout", "com.sun.jndi.ldap.read.timeout"); // authentication strategy final String rawAuthenticationStrategy = configurationContext.getProperty("Authentication Strategy"); final LdapAuthenticationStrategy authenticationStrategy; try { authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException(String.format( "Unrecognized authentication strategy '%s'. Possible values are [%s]", rawAuthenticationStrategy, StringUtils.join(LdapAuthenticationStrategy.values(), ", "))); } switch (authenticationStrategy) { case ANONYMOUS: context.setAnonymousReadOnly(true); break; default: final String userDn = configurationContext.getProperty("Manager DN"); final String password = configurationContext.getProperty("Manager Password"); context.setUserDn(userDn); context.setPassword(password); switch (authenticationStrategy) { case SIMPLE: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); break; case LDAPS: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); // indicate a secure connection baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); // get the configured ssl context final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext); if (ldapsSslContext != null) { // initialize the ldaps socket factory prior to use LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory()); baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName()); } break; case START_TLS: final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); // shutdown gracefully final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully"); if (StringUtils.isNotBlank(rawShutdownGracefully)) { final boolean shutdownGracefully = Boolean.TRUE.toString() .equalsIgnoreCase(rawShutdownGracefully); tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully); } // get the configured ssl context final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext); if (startTlsSslContext != null) { tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory()); } // set the authentication strategy context.setAuthenticationStrategy(tlsAuthenticationStrategy); break; } break; } // referrals final String rawReferralStrategy = configurationContext.getProperty("Referral Strategy"); final ReferralStrategy referralStrategy; try { referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("Unrecognized referral strategy '%s'. Possible values are [%s]", rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", "))); } // using the value as this needs to be the lowercase version while the value is configured with the enum constant context.setReferral(referralStrategy.getValue()); // url final String urls = configurationContext.getProperty("Url"); if (StringUtils.isBlank(urls)) { throw new SecurityProviderCreationException("LDAP identity provider 'Url' must be specified."); } // connection context.setUrls(StringUtils.split(urls)); // search criteria final String userSearchBase = configurationContext.getProperty("User Search Base"); final String userSearchFilter = configurationContext.getProperty("User Search Filter"); if (StringUtils.isBlank(userSearchBase) || StringUtils.isBlank(userSearchFilter)) { throw new SecurityProviderCreationException( "LDAP identity provider 'User Search Base' and 'User Search Filter' must be specified."); } final LdapUserSearch userSearch = new FilterBasedLdapUserSearch(userSearchBase, userSearchFilter, context); // bind final BindAuthenticator authenticator = new BindAuthenticator(context); authenticator.setUserSearch(userSearch); // identity strategy final String rawIdentityStrategy = configurationContext.getProperty("Identity Strategy"); if (StringUtils.isBlank(rawIdentityStrategy)) { logger.info(String.format("Identity Strategy is not configured, defaulting strategy to %s.", IdentityStrategy.USE_DN)); // if this value is not configured, default to use dn which was the previous implementation identityStrategy = IdentityStrategy.USE_DN; } else { try { // attempt to get the configured identity strategy identityStrategy = IdentityStrategy.valueOf(rawIdentityStrategy); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("Unrecognized identity strategy '%s'. Possible values are [%s]", rawIdentityStrategy, StringUtils.join(IdentityStrategy.values(), ", "))); } } // set the base environment is necessary if (!baseEnvironment.isEmpty()) { context.setBaseEnvironmentProperties(baseEnvironment); } try { // handling initializing beans context.afterPropertiesSet(); authenticator.afterPropertiesSet(); } catch (final Exception e) { throw new SecurityProviderCreationException(e.getMessage(), e); } // create the underlying provider ldapAuthenticationProvider = new LdapAuthenticationProvider(authenticator); }
From source file:org.apache.nifi.registry.security.ldap.tenants.LdapUserGroupProvider.java
@Override public void onConfigured(final AuthorizerConfigurationContext configurationContext) throws SecurityProviderCreationException { final LdapContextSource context = new LdapContextSource(); final Map<String, Object> baseEnvironment = new HashMap<>(); // connect/read time out setTimeout(configurationContext, baseEnvironment, PROP_CONNECT_TIMEOUT, "com.sun.jndi.ldap.connect.timeout"); setTimeout(configurationContext, baseEnvironment, PROP_READ_TIMEOUT, "com.sun.jndi.ldap.read.timeout"); // authentication strategy final PropertyValue rawAuthenticationStrategy = configurationContext .getProperty(PROP_AUTHENTICATION_STRATEGY); final LdapAuthenticationStrategy authenticationStrategy; try {//from www .ja v a2s . co m authenticationStrategy = LdapAuthenticationStrategy.valueOf(rawAuthenticationStrategy.getValue()); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("Unrecognized authentication strategy '%s'. Possible values are [%s]", rawAuthenticationStrategy.getValue(), StringUtils.join(LdapAuthenticationStrategy.values(), ", "))); } switch (authenticationStrategy) { case ANONYMOUS: context.setAnonymousReadOnly(true); break; default: final String userDn = configurationContext.getProperty(PROP_MANAGER_DN).getValue(); final String password = configurationContext.getProperty(PROP_MANAGER_PASSWORD).getValue(); context.setUserDn(userDn); context.setPassword(password); switch (authenticationStrategy) { case SIMPLE: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); break; case LDAPS: context.setAuthenticationStrategy(new SimpleDirContextAuthenticationStrategy()); // indicate a secure connection baseEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); // get the configured ssl context final SSLContext ldapsSslContext = getConfiguredSslContext(configurationContext); if (ldapsSslContext != null) { // initialize the ldaps socket factory prior to use LdapsSocketFactory.initialize(ldapsSslContext.getSocketFactory()); baseEnvironment.put("java.naming.ldap.factory.socket", LdapsSocketFactory.class.getName()); } break; case START_TLS: final AbstractTlsDirContextAuthenticationStrategy tlsAuthenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); // shutdown gracefully final String rawShutdownGracefully = configurationContext.getProperty("TLS - Shutdown Gracefully") .getValue(); if (StringUtils.isNotBlank(rawShutdownGracefully)) { final boolean shutdownGracefully = Boolean.TRUE.toString() .equalsIgnoreCase(rawShutdownGracefully); tlsAuthenticationStrategy.setShutdownTlsGracefully(shutdownGracefully); } // get the configured ssl context final SSLContext startTlsSslContext = getConfiguredSslContext(configurationContext); if (startTlsSslContext != null) { tlsAuthenticationStrategy.setSslSocketFactory(startTlsSslContext.getSocketFactory()); } // set the authentication strategy context.setAuthenticationStrategy(tlsAuthenticationStrategy); break; } break; } // referrals final String rawReferralStrategy = configurationContext.getProperty(PROP_REFERRAL_STRATEGY).getValue(); final ReferralStrategy referralStrategy; try { referralStrategy = ReferralStrategy.valueOf(rawReferralStrategy); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("Unrecognized referral strategy '%s'. Possible values are [%s]", rawReferralStrategy, StringUtils.join(ReferralStrategy.values(), ", "))); } // using the value as this needs to be the lowercase version while the value is configured with the enum constant context.setReferral(referralStrategy.getValue()); // url final String urls = configurationContext.getProperty(PROP_URL).getValue(); if (StringUtils.isBlank(urls)) { throw new SecurityProviderCreationException("LDAP identity provider 'Url' must be specified."); } // connection context.setUrls(StringUtils.split(urls)); // raw user search base final PropertyValue rawUserSearchBase = configurationContext.getProperty(PROP_USER_SEARCH_BASE); final PropertyValue rawUserObjectClass = configurationContext.getProperty(PROP_USER_OBJECT_CLASS); final PropertyValue rawUserSearchScope = configurationContext.getProperty(PROP_USER_SEARCH_SCOPE); // if loading the users, ensure the object class set if (rawUserSearchBase.isSet() && !rawUserObjectClass.isSet()) { throw new SecurityProviderCreationException( "LDAP user group provider 'User Object Class' must be specified when 'User Search Base' is set."); } // if loading the users, ensure the search scope is set if (rawUserSearchBase.isSet() && !rawUserSearchScope.isSet()) { throw new SecurityProviderCreationException( "LDAP user group provider 'User Search Scope' must be specified when 'User Search Base' is set."); } // user search criteria userSearchBase = rawUserSearchBase.getValue(); userObjectClass = rawUserObjectClass.getValue(); userSearchFilter = configurationContext.getProperty(PROP_USER_SEARCH_FILTER).getValue(); userIdentityAttribute = configurationContext.getProperty(PROP_USER_IDENTITY_ATTRIBUTE).getValue(); userGroupNameAttribute = configurationContext.getProperty(PROP_USER_GROUP_ATTRIBUTE).getValue(); userGroupReferencedGroupAttribute = configurationContext .getProperty(PROP_USER_GROUP_REFERENCED_GROUP_ATTRIBUTE).getValue(); try { userSearchScope = SearchScope.valueOf(rawUserSearchScope.getValue()); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("Unrecognized user search scope '%s'. Possible values are [%s]", rawUserSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", "))); } // determine user behavior useDnForUserIdentity = StringUtils.isBlank(userIdentityAttribute); performUserSearch = StringUtils.isNotBlank(userSearchBase); // raw group search criteria final PropertyValue rawGroupSearchBase = configurationContext.getProperty(PROP_GROUP_SEARCH_BASE); final PropertyValue rawGroupObjectClass = configurationContext.getProperty(PROP_GROUP_OBJECT_CLASS); final PropertyValue rawGroupSearchScope = configurationContext.getProperty(PROP_GROUP_SEARCH_SCOPE); // if loading the groups, ensure the object class is set if (rawGroupSearchBase.isSet() && !rawGroupObjectClass.isSet()) { throw new SecurityProviderCreationException( "LDAP user group provider 'Group Object Class' must be specified when 'Group Search Base' is set."); } // if loading the groups, ensure the search scope is set if (rawGroupSearchBase.isSet() && !rawGroupSearchScope.isSet()) { throw new SecurityProviderCreationException( "LDAP user group provider 'Group Search Scope' must be specified when 'Group Search Base' is set."); } // group search criteria groupSearchBase = rawGroupSearchBase.getValue(); groupObjectClass = rawGroupObjectClass.getValue(); groupSearchFilter = configurationContext.getProperty(PROP_GROUP_SEARCH_FILTER).getValue(); groupNameAttribute = configurationContext.getProperty(PROP_GROUP_NAME_ATTRIBUTE).getValue(); groupMemberAttribute = configurationContext.getProperty(PROP_GROUP_MEMBER_ATTRIBUTE).getValue(); groupMemberReferencedUserAttribute = configurationContext .getProperty(PROP_GROUP_MEMBER_REFERENCED_USER_ATTRIBUTE).getValue(); try { groupSearchScope = SearchScope.valueOf(rawGroupSearchScope.getValue()); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("Unrecognized group search scope '%s'. Possible values are [%s]", rawGroupSearchScope.getValue(), StringUtils.join(SearchScope.values(), ", "))); } // determine group behavior useDnForGroupName = StringUtils.isBlank(groupNameAttribute); performGroupSearch = StringUtils.isNotBlank(groupSearchBase); // ensure we are either searching users or groups (at least one must be specified) if (!performUserSearch && !performGroupSearch) { throw new SecurityProviderCreationException( "LDAP user group provider 'User Search Base' or 'Group Search Base' must be specified."); } // ensure group member attribute is set if searching groups but not users if (performGroupSearch && !performUserSearch && StringUtils.isBlank(groupMemberAttribute)) { throw new SecurityProviderCreationException( "'Group Member Attribute' is required when searching groups but not users."); } // ensure that performUserSearch is set when groupMemberReferencedUserAttribute is specified if (StringUtils.isNotBlank(groupMemberReferencedUserAttribute) && !performUserSearch) { throw new SecurityProviderCreationException( "''User Search Base' must be set when specifying 'Group Member Attribute - Referenced User Attribute'."); } // ensure that performGroupSearch is set when userGroupReferencedGroupAttribute is specified if (StringUtils.isNotBlank(userGroupReferencedGroupAttribute) && !performGroupSearch) { throw new SecurityProviderCreationException( "'Group Search Base' must be set when specifying 'User Group Name Attribute - Referenced Group Attribute'."); } // get the page size if configured final PropertyValue rawPageSize = configurationContext.getProperty(PROP_PAGE_SIZE); if (rawPageSize.isSet() && StringUtils.isNotBlank(rawPageSize.getValue())) { pageSize = rawPageSize.asInteger(); } // extract the identity mappings from nifi-registry.properties if any are provided identityMappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties)); // set the base environment is necessary if (!baseEnvironment.isEmpty()) { context.setBaseEnvironmentProperties(baseEnvironment); } try { // handling initializing beans context.afterPropertiesSet(); } catch (final Exception e) { throw new SecurityProviderCreationException(e.getMessage(), e); } final PropertyValue rawSyncInterval = configurationContext.getProperty(PROP_SYNC_INTERVAL); final long syncInterval; if (rawSyncInterval.isSet()) { try { syncInterval = FormatUtils.getTimeDuration(rawSyncInterval.getValue(), TimeUnit.MILLISECONDS); } catch (final IllegalArgumentException iae) { throw new SecurityProviderCreationException( String.format("The %s '%s' is not a valid time duration", PROP_SYNC_INTERVAL, rawSyncInterval.getValue())); } } else { throw new SecurityProviderCreationException("The 'Sync Interval' must be specified."); } try { // perform the initial load, tenants must be loaded as the configured UserGroupProvider is supplied // to the AccessPolicyProvider for granting initial permissions load(context); // ensure the tenants were successfully synced if (tenants.get() == null) { throw new SecurityProviderCreationException("Unable to sync users and groups."); } // schedule the background thread to load the users/groups ldapSync.scheduleWithFixedDelay(() -> load(context), syncInterval, syncInterval, TimeUnit.MILLISECONDS); } catch (final AuthorizationAccessException e) { throw new SecurityProviderCreationException(e); } }
From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java
@Override public void configure(String id, Properties properties) throws PIPException { /*//from w ww . ja va 2 s.c om * Handle the standard properties */ super.configure(id, properties); String propertyPrefix = id + "."; /* * Configure the LDAP environment: I think the only required property is the provider_url */ if (!this.configureStringProperty(propertyPrefix, Context.PROVIDER_URL, properties, null)) { throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No " + propertyPrefix + Context.PROVIDER_URL); } this.configureStringProperty(propertyPrefix, Context.AUTHORITATIVE, properties, null); this.configureIntegerProperty(propertyPrefix, Context.BATCHSIZE, properties, null); this.configureStringProperty(propertyPrefix, Context.DNS_URL, properties, null); this.configureStringProperty(propertyPrefix, Context.INITIAL_CONTEXT_FACTORY, properties, DEFAULT_CONTEXT_FACTORY); this.configureStringProperty(propertyPrefix, Context.LANGUAGE, properties, null); this.configureStringProperty(propertyPrefix, Context.OBJECT_FACTORIES, properties, null); this.configureStringProperty(propertyPrefix, Context.REFERRAL, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_AUTHENTICATION, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_CREDENTIALS, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_PRINCIPAL, properties, null); this.configureStringProperty(propertyPrefix, Context.SECURITY_PROTOCOL, properties, null); this.configureStringProperty(propertyPrefix, Context.STATE_FACTORIES, properties, null); this.configureStringProperty(propertyPrefix, Context.URL_PKG_PREFIXES, properties, null); String ldapScopeValue = properties.getProperty(propertyPrefix + PROP_LDAP_SCOPE, DEFAULT_SCOPE); if (LDAP_SCOPE_SUBTREE.equals(ldapScopeValue)) { this.ldapScope = SearchControls.SUBTREE_SCOPE; } else if (LDAP_SCOPE_OBJECT.equals(ldapScopeValue)) { this.ldapScope = SearchControls.OBJECT_SCOPE; } else if (LDAP_SCOPE_ONELEVEL.equals(ldapScopeValue)) { this.ldapScope = SearchControls.ONELEVEL_SCOPE; } else { this.logger.warn("Invalid LDAP Scope value '" + ldapScopeValue + "'; using " + DEFAULT_SCOPE); this.ldapScope = SearchControls.SUBTREE_SCOPE; } /* * Get list of resolvers defined for this LDAP Engine */ String resolversList = properties.getProperty(propertyPrefix + PROP_RESOLVERS); if (resolversList == null || resolversList.isEmpty()) { throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No " + propertyPrefix + PROP_RESOLVERS); } /* * Iterate the resolvers */ for (String resolver : Splitter.on(',').trimResults().omitEmptyStrings().split(resolversList)) { /* * Get the LDAPResolver for this LDAPEngine */ String resolverClassName = properties .getProperty(propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname"); if (resolverClassName == null) { throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No " + propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname"); } LDAPResolver ldapResolverNew = null; try { Class<?> classResolver = Class.forName(resolverClassName); if (!LDAPResolver.class.isAssignableFrom(classResolver)) { this.logger.error("LDAPResolver class " + resolverClassName + " does not implement " + LDAPResolver.class.getCanonicalName()); throw new PIPException("LDAPResolver class " + resolverClassName + " does not implement " + LDAPResolver.class.getCanonicalName()); } ldapResolverNew = LDAPResolver.class.cast(classResolver.newInstance()); } catch (Exception ex) { this.logger.error("Exception instantiating LDAPResolver for class '" + resolverClassName + "': " + ex.getMessage(), ex); throw new PIPException("Exception instantiating LDAPResolver for class '" + resolverClassName + "'", ex); } assert ldapResolverNew != null; ldapResolverNew.configure(propertyPrefix + PROP_RESOLVER + "." + resolver, properties, this.getIssuer()); this.ldapResolvers.add(ldapResolverNew); } }
From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java
protected DirContext getConnection() { //JNDI boilerplate to connect to an initial context DirContext context = (DirContext) contexts.get("context"); if (context == null) { Hashtable jndienv = new Hashtable(); jndienv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); jndienv.put(Context.SECURITY_AUTHENTICATION, "simple"); if (url.startsWith("ldaps")) { // Handle SSL connections String newurl = url.substring(0, 4) + url.substring(5); jndienv.put(Context.SECURITY_PROTOCOL, "ssl"); jndienv.put(Context.PROVIDER_URL, newurl); } else {/* ww w. j a v a 2 s .co m*/ jndienv.put(Context.PROVIDER_URL, url); } if (logonid != null) jndienv.put(Context.SECURITY_PRINCIPAL, logonid); if (logonpassword != null) jndienv.put(Context.SECURITY_CREDENTIALS, logonpassword); try { context = new InitialDirContext(jndienv); } catch (NamingException nex) { log.error("LDAPGroupStore: unable to get context", nex); } contexts.put("context", context); } return context; }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Creates an InitialLdapContext by logging into the configured Ldap Server using the provided * username and credential.// www. j a v a 2s . c om * * @return the Initial Ldap Context to be used to perform searches, etc. * @throws NamingException LDAP binding error. */ protected InitialLdapContext createLdapInitialContext(String securityPrincipal, String securityCredential) throws NamingException { Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory()); env.setProperty(Context.SECURITY_AUTHENTICATION, getSecurityAuthentication()); env.setProperty(Context.PROVIDER_URL, getProviderUrl()); env.setProperty(Context.SECURITY_PROTOCOL, (getSecurityProtocol() == null ? "" : getSecurityProtocol())); // Set defaults for key values if they are missing String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (factoryName == null) { factoryName = "com.sun.jndi.ldap.LdapCtxFactory"; env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName); } String authType = env.getProperty(Context.SECURITY_AUTHENTICATION); if (authType == null) env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); String protocol = env.getProperty(Context.SECURITY_PROTOCOL); String providerURL = getProviderUrl(); // Use localhost if providerUrl not set if (providerURL == null) { providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389"); } else { // In case user configured provided URL if (providerURL.startsWith("ldaps")) { protocol = "ssl"; env.setProperty(Context.SECURITY_PROTOCOL, "ssl"); } } env.setProperty(Context.PROVIDER_URL, providerURL); if (securityPrincipal != null && !"".equals(securityPrincipal)) env.setProperty(Context.SECURITY_PRINCIPAL, securityPrincipal); if (securityCredential != null && !"".equals(securityCredential)) env.put(Context.SECURITY_CREDENTIALS, securityCredential); // always follow referrals transparently env.put(Context.REFERRAL, "follow"); // Logon into LDAP server if (logger.isDebugEnabled()) logger.debug("Logging into LDAP server, env=" + env); InitialLdapContext ctx = new InitialLdapContext(env, null); if (logger.isDebugEnabled()) logger.debug("Logged into LDAP server, " + ctx); return ctx; }
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private LdapContext getLdapContext() throws NamingException, AuthenticationException { if (config == null) { throw new NamingException("LDAP not configured"); }/*w ww .j ava2 s . c o m*/ if (StringUtils.isBlank(config.getProviderUrl())) { throw new NamingException("No LDAP server available"); } if (StringUtils.isBlank(config.getUsername()) || StringUtils.isBlank(config.getPassword())) { throw new AuthenticationException("No LDAP credentials available"); } String ctxFactory = config.getCtxFactory(); if (StringUtils.isBlank(ctxFactory)) { ctxFactory = DEFAULT_CONTEXT_FACTORY; } String authentication = config.getAuthentication(); if (StringUtils.isBlank(authentication)) { authentication = SIMPLE_AUTHENTICATION; } Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory); env.put(Context.PROVIDER_URL, config.getProviderUrl()); env.put(Context.SECURITY_PRINCIPAL, config.getUsername()); env.put(Context.SECURITY_CREDENTIALS, config.getPassword()); env.put(Context.SECURITY_AUTHENTICATION, authentication); if (StringUtils.isNotBlank(config.getReferral())) { env.put(Context.REFERRAL, config.getReferral()); } if (config.getProviderUrl().startsWith(LDAPS_SCHEME)) { env.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$ if (config.isSslNoVerify()) { env.put(JNDI_SOCKET_FACTORY, LDAPTrustAllSocketFactory.class.getName()); } } // Gemini-specific properties env.put(JNDIConstants.BUNDLE_CONTEXT, FrameworkUtil.getBundle(LDAPClient.class).getBundleContext()); // com.sun.jndi.ldap.LdapCtxFactory specific properties env.put(READ_TIMEOUT, DEFAULT_READ_TIMEOUT); env.put(USE_CONNECTION_POOLING, "true"); //$NON-NLS-1$ // extremly ugly classloading workaround: // com.sun.jndi.ldap.LdapCtxFactory uses Class.forName() to load the socket factory, shame on them! InitialLdapContext ctx = null; ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(LDAPTrustAllSocketFactory.class.getClassLoader()); ctx = new InitialLdapContext(env, null); } finally { if (classloader != null) { Thread.currentThread().setContextClassLoader(classloader); } } return ctx; }
From source file:org.exist.security.realm.ldap.LdapContextFactory.java
public LdapContext getLdapContext(String username, final String password, final Map<String, Object> additionalEnv) throws NamingException { if (url == null) { throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>"); }/* ww w .jav a 2 s . c o m*/ if (StringUtils.isBlank(password)) { throw new IllegalStateException("Password for LDAP authentication may not be empty."); } if (username != null && principalPattern != null) { username = principalPatternFormat.format(new String[] { username }); } final Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.SECURITY_AUTHENTICATION, authentication); if (ssl) { env.put(Context.SECURITY_PROTOCOL, "ssl"); } if (username != null) { env.put(Context.SECURITY_PRINCIPAL, username); } if (password != null) { env.put(Context.SECURITY_CREDENTIALS, password); } env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName); env.put(Context.PROVIDER_URL, url); //Absolutely nessecary for working with Active Directory env.put("java.naming.ldap.attributes.binary", "objectSid"); // the following is helpful in debugging errors //env.put("com.sun.jndi.ldap.trace.ber", System.err); // Only pool connections for system contexts if (usePooling && username != null && username.equals(systemUsername)) { // Enable connection pooling env.put(SUN_CONNECTION_POOLING_PROPERTY, "true"); } if (additionalEnv != null) { env.putAll(additionalEnv); } if (LOG.isDebugEnabled()) { LOG.debug("Initializing LDAP context using URL [" + url + "] and username [" + username + "] " + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]"); } return new InitialLdapContext(env, null); }