List of usage examples for javax.naming Context SECURITY_CREDENTIALS
String SECURITY_CREDENTIALS
To view the source code for javax.naming Context SECURITY_CREDENTIALS.
Click Source Link
From source file:jp.terasoluna.fw.web.jndi.DefaultJndiSupport.java
/** * JndiTemplate??//from w ww .j a v a2 s . c o m */ public void initialize() { // JNDI???????Weblogic?? if (jndiEnvironmentMap != null) { // jndiEnvironmentMap??? String factory = jndiEnvironmentMap.get(JNDI_FACTORY_KEY); String url = jndiEnvironmentMap.get(JNDI_URL_KEY); String username = jndiEnvironmentMap.get(JNDI_USERNAME_KEY); String password = jndiEnvironmentMap.get(JNDI_PASSWORD_KEY); Properties environment = new Properties(); environment.put(Context.INITIAL_CONTEXT_FACTORY, factory); environment.put(Context.PROVIDER_URL, url); if (!"".equals(username) && username != null) { environment.put(Context.SECURITY_PRINCIPAL, username); if (password == null) { password = ""; } environment.put(Context.SECURITY_CREDENTIALS, password); } // ?? getJndiTemplate().setEnvironment(environment); // if (log.isInfoEnabled()) { log.info("Initialize Weblogic JNDI Resource"); log.info(Context.INITIAL_CONTEXT_FACTORY + " = " + factory); log.info(Context.PROVIDER_URL + " = " + url); log.info(Context.SECURITY_PRINCIPAL + " = " + username); log.info(Context.SECURITY_CREDENTIALS + " = " + password); } } }
From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java
private DirContext createAuthenticatedContext() { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userName); env.put(Context.SECURITY_CREDENTIALS, password); return createContext(env); }
From source file:org.kitodo.services.data.LdapServerService.java
/** * Check if connection with login and password possible. * * @param user/*from w ww .j av a 2s. co m*/ * User object * @param password * String * @return Login correct or not */ public boolean isUserPasswordCorrect(User user, String password) { logger.debug("start login session with ldap"); Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer()); // Start TLS if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) { logger.debug("use TLS for auth"); env.put("java.naming.ldap.version", "3"); LdapContext ctx = null; StartTlsResponse tls = null; try { ctx = new InitialLdapContext(env, null); // Authentication must be performed over a secure channel tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tls.negotiate(); // Authenticate via SASL EXTERNAL mechanism using client X.509 // certificate contained in JVM keystore ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user)); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); ctx.reconnect(null); return true; // Perform search for privileged attributes under authenticated // context } catch (IOException e) { logger.error("TLS negotiation error:", e); return false; } catch (NamingException e) { logger.error("JNDI error:", e); return false; } finally { if (tls != null) { try { // Tear down TLS connection tls.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (ctx != null) { try { // Close LDAP connection ctx.close(); } catch (NamingException e) { logger.error(e.getMessage(), e); } } } } else { logger.debug("don't use TLS for auth"); if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) { env.put(Context.SECURITY_AUTHENTICATION, "none"); // TODO auf passwort testen } else { env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user)); env.put(Context.SECURITY_CREDENTIALS, password); } logger.debug("ldap environment set"); try { logger.debug("start classic ldap authentication"); logger.debug("user DN is {}", buildUserDN(user)); if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == null) { logger.debug("ldap attribute to test is null"); DirContext ctx = new InitialDirContext(env); ctx.close(); return true; } else { logger.debug("ldap attribute to test is not null"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(buildUserDN(user)); Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST)); logger.debug("ldap attributes set"); String test = (String) la.get(0); if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) { logger.debug("ldap ok"); ctx.close(); return true; } else { logger.debug("ldap not ok"); ctx.close(); return false; } } } catch (NamingException e) { logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e); return false; } } }
From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java
/** * Changes the password for the current user. The username is obtained from the security * context. <p> If the old password is supplied, the update will be made by rebinding as the * user, thus modifying the password using the user's permissions. If <code>oldPassword</code> * is null, the update will be attempted using a standard read/write context supplied by the * context source. </p>// ww w . j a va 2 s . c o m * * @param oldPassword the old password * @param newPassword the new value of the password. */ public void changePassword(final String oldPassword, final String newPassword) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assert.notNull(authentication, "No authentication object found in security context. Can't change current user's password!"); String username = authentication.getName(); logger.debug("Changing password for user '" + username); final DistinguishedName dn = usernameMapper.buildDn(username); final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(dn, passwordChange); return; } template.executeReadWrite(new ContextExecutor() { public Object executeWithContext(DirContext dirCtx) throws NamingException { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(dn, ctx).toString()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword); // TODO: reconnect doesn't appear to actually change the // credentials try { ctx.reconnect(null); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException("Authentication for password change failed."); } ctx.modifyAttributes(dn, passwordChange); return null; } }); }
From source file:org.lsc.jndi.JndiServices.java
private void initConnection() throws NamingException, IOException { // log new connection with it's details logConnectingTo(connProps);//from ww w . j ava 2 s. co m /* should we negotiate TLS? */ if (connProps.get(TLS_CONFIGURATION) != null && (Boolean) connProps.get(TLS_CONFIGURATION)) { /* if we're going to do TLS, we mustn't BIND before the STARTTLS operation * so we remove credentials from the properties to stop JNDI from binding */ /* duplicate properties to avoid changing them (they are used as a cache key in getInstance() */ Properties localConnProps = new Properties(); localConnProps.putAll(connProps); String jndiContextAuthentication = localConnProps.getProperty(Context.SECURITY_AUTHENTICATION); String jndiContextPrincipal = localConnProps.getProperty(Context.SECURITY_PRINCIPAL); String jndiContextCredentials = localConnProps.getProperty(Context.SECURITY_CREDENTIALS); localConnProps.remove(Context.SECURITY_AUTHENTICATION); localConnProps.remove(Context.SECURITY_PRINCIPAL); localConnProps.remove(Context.SECURITY_CREDENTIALS); /* open the connection */ ctx = new InitialLdapContext(localConnProps, null); /* initiate the STARTTLS extended operation */ try { tlsResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest()); tlsResponse.negotiate(); } catch (IOException e) { LOGGER.error("Error starting TLS encryption on connection to {}", localConnProps.getProperty(Context.PROVIDER_URL)); LOGGER.debug(e.toString(), e); throw e; } catch (NamingException e) { LOGGER.error("Error starting TLS encryption on connection to {}", localConnProps.getProperty(Context.PROVIDER_URL)); LOGGER.debug(e.toString(), e); throw e; } /* now we add the credentials back to the context, to BIND once TLS is started */ ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiContextAuthentication); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, jndiContextPrincipal); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, jndiContextCredentials); } else { /* don't start TLS, just connect normally (this can be on ldap:// or ldaps://) */ ctx = new InitialLdapContext(connProps, null); } /* get LDAP naming context */ try { namingContext = new LdapUrl((String) ctx.getEnvironment().get(Context.PROVIDER_URL)); } catch (LdapURLEncodingException e) { LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); throw new NamingException(e.getMessage()); } /* handle options */ contextDn = namingContext.getDn() != null ? namingContext.getDn() : null; String pageSizeStr = (String) ctx.getEnvironment().get("java.naming.ldap.pageSize"); if (pageSizeStr != null) { pageSize = Integer.parseInt(pageSizeStr); } else { pageSize = -1; } sortedBy = (String) ctx.getEnvironment().get("java.naming.ldap.sortedBy"); String recursiveDeleteStr = (String) ctx.getEnvironment().get("java.naming.recursivedelete"); if (recursiveDeleteStr != null) { recursiveDelete = Boolean.parseBoolean(recursiveDeleteStr); } else { recursiveDelete = false; } /* Load SyncRepl response control */ LdapApiService ldapApiService = LdapApiServiceFactory.getSingleton(); ControlFactory<?> factory = new SyncStateValueFactory(ldapApiService); ldapApiService.registerControl(factory); /* Load Persistent Search response control */ factory = new PersistentSearchFactory(ldapApiService); ldapApiService.registerControl(factory); }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPBindIdentityStore.java
/** * This store performs a bind to the configured LDAP server and closes the connection immediately. * If the connection fails, an exception is thrown, otherwise this method returns silentrly * * @return true if the bind is successful *///from ww w. j av a 2 s.c o m public boolean bind(String username, String password, BindContext bindCtx) throws SSOAuthenticationException { String dn = null; try { // first try to retrieve the user using an known user dn = selectUserDN(username); if (dn == null || "".equals(dn)) { if (logger.isDebugEnabled()) logger.debug("No DN found for user : " + username); return false; } logger.debug("user dn = " + dn); // Create context without binding! InitialLdapContext ctx = this.createLdapInitialContext(null, null); Control[] ldapControls = null; try { ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); if (isPasswordPolicySupport()) { // Configure request control for password policy: ctx.reconnect(new Control[] { new BasicControl(PasswordPolicyResponseControl.CONTROL_OID) }); } else { ctx.reconnect(new Control[] {}); } // Get response controls from reconnect BEFORE dn search, or they're lost ldapControls = ctx.getResponseControls(); // Bind to LDAP an check for authentication warning/errors reported in password policy control: if (validateBindWithSearch) { selectUserDN(ctx, username); // Perhaps controls are not send during reconnet, try to get them now if (ldapControls == null || ldapControls.length == 0) ldapControls = ctx.getResponseControls(); } if (logger.isTraceEnabled()) logger.trace("LDAP Bind with user credentials succeeded"); } catch (AuthenticationException e) { if (logger.isDebugEnabled()) logger.debug("LDAP Bind Authentication error : " + e.getMessage(), e); return false; } finally { if (isPasswordPolicySupport()) { // If an exception occurred, controls are not retrieved yet if (ldapControls == null || ldapControls.length == 0) ldapControls = ctx.getResponseControls(); // Check password policy LDAP Control PasswordPolicyResponseControl ppolicyCtrl = decodePasswordPolicyControl(ldapControls); if (ppolicyCtrl != null) addPasswordPolicyToBindCtx(ppolicyCtrl, bindCtx); } ctx.close(); } return true; } catch (Exception e) { throw new SSOAuthenticationException( "Cannot bind as user : " + username + " [" + dn + "]" + e.getMessage(), e); } }
From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java
public void testRunAsMethod() throws Exception { log.debug("+++ testRunAsMethod()"); Properties env = new Properties(); env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory"); env.setProperty(Context.SECURITY_PRINCIPAL, "jduke"); env.setProperty(Context.SECURITY_CREDENTIALS, "theduke"); InitialContext ctx = new InitialContext(env); Object obj = ctx.lookup("jacc/Secured"); obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class); SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj; log.debug("Found SecuredServiceRemoteHome"); SecuredServiceRemote bean = home.create(); log.debug("Created SecuredServiceRemote"); Principal callerIdentity = new SimplePrincipal("jduke"); Principal runAsIdentity = new SimplePrincipal("runAsUser"); HashSet expectedCallerRoles = new HashSet(); expectedCallerRoles.add("groupMemberCaller"); expectedCallerRoles.add("userCaller"); expectedCallerRoles.add("allAuthCaller"); expectedCallerRoles.add("webUser"); HashSet expectedRunAsRoles = new HashSet(); expectedRunAsRoles.add("identitySubstitutionCaller"); expectedRunAsRoles.add("extraRunAsRole"); CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles); bean.runAsMethod(info);/*w ww . j a v a 2 s . c o m*/ bean.remove(); }
From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java
@SuppressWarnings("unchecked") public void updateCredential(String connectionPassword) { /*/*w w w .j av a 2s .c om*/ * update the password otherwise it is not possible to connect again if admin password * changed */ this.environment.put(Context.SECURITY_CREDENTIALS, connectionPassword); }
From source file:org.springframework.ldap.odm.tools.SchemaToJava.java
private static ObjectSchema readSchema(String url, String user, String pass, SyntaxToJavaClass syntaxToJavaClass, Set<String> binarySet, Set<String> objectClasses) throws NamingException, ClassNotFoundException { // Set up environment Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.PROVIDER_URL, url); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); if (user != null) { env.put(Context.SECURITY_PRINCIPAL, user); }//from w w w . java 2 s .c o m if (pass != null) { env.put(Context.SECURITY_CREDENTIALS, pass); } DirContext context = new InitialDirContext(env); DirContext schemaContext = context.getSchema(""); SchemaReader reader = new SchemaReader(schemaContext, syntaxToJavaClass, binarySet); ObjectSchema schema = reader.getObjectSchema(objectClasses); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Schema - %1$s", schema.toString())); } return schema; }