List of usage examples for javax.security.auth.login LoginContext LoginContext
public LoginContext(String name, CallbackHandler callbackHandler) throws LoginException
From source file:org.lsc.jndi.JndiServices.java
public static Properties getLdapProperties(LdapConnectionType connection) throws LscConfigurationException { Properties props = new Properties(); props.setProperty(DirContext.INITIAL_CONTEXT_FACTORY, (connection.getFactory() != null ? connection.getFactory() : "com.sun.jndi.ldap.LdapCtxFactory")); props.put(TLS_CONFIGURATION, connection.isTlsActivated()); if (connection.getUsername() != null) { props.setProperty(DirContext.SECURITY_AUTHENTICATION, connection.getAuthentication().value()); props.setProperty(DirContext.SECURITY_PRINCIPAL, connection.getUsername()); if (connection.getAuthentication().equals(LdapAuthenticationType.GSSAPI)) { if (System.getProperty("java.security.krb5.conf") != null) { throw new RuntimeException("Multiple Kerberos connections not supported (existing value: " + System.getProperty("java.security.krb5.conf") + "). Need to set another LSC instance or unset system property !"); } else { System.setProperty("java.security.krb5.conf", new File(Configuration.getConfigurationDirectory(), "krb5.ini").getAbsolutePath()); }/*from w w w. ja va2 s.co m*/ if (System.getProperty("java.security.auth.login.config") != null) { throw new RuntimeException("Multiple JAAS not supported (existing value: " + System.getProperty("java.security.auth.login.config") + "). Need to set another LSC instance or unset system property !"); } else { System.setProperty("java.security.auth.login.config", new File(Configuration.getConfigurationDirectory(), "gsseg_jaas.conf") .getAbsolutePath()); } props.setProperty("javax.security.sasl.server.authentication", "" + connection.isSaslMutualAuthentication()); // props.put("java.naming.security.sasl.authorizationId", "dn:" + connection.getUsername()); props.put("javax.security.auth.useSubjectCredsOnly", "true"); props.put("com.sun.jndi.ldap.trace.ber", System.err); //debug trace props.setProperty("javax.security.sasl.qop", connection.getSaslQop().value()); try { LoginContext lc = new LoginContext(JndiServices.class.getName(), new KerberosCallbackHandler(connection.getUsername(), connection.getPassword())); lc.login(); } catch (LoginException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { props.setProperty(DirContext.SECURITY_CREDENTIALS, connection.getPassword()); } } else { props.setProperty(DirContext.SECURITY_AUTHENTICATION, "none"); } try { LdapUrl connectionUrl = new LdapUrl(connection.getUrl()); if (connectionUrl.getHost() == null) { if (LOGGER.isDebugEnabled()) LOGGER.debug( "Hostname is empty in LDAP URL, will try to lookup through the naming context ..."); String domainExt = convertToDomainExtension(connectionUrl.getDn()); if (domainExt != null) { String hostname = lookupLdapSrvThroughDNS("_ldap._tcp." + domainExt); if (hostname != null) { connectionUrl.setHost(hostname.substring(0, hostname.indexOf(":"))); connectionUrl.setPort(Integer.parseInt(hostname.substring(hostname.indexOf(":") + 1))); connection.setUrl(connectionUrl.toString()); } } } } catch (LdapURLEncodingException e) { throw new LscConfigurationException(e); } props.setProperty(DirContext.PROVIDER_URL, connection.getUrl()); if (connection.getReferral() != null) { props.setProperty(DirContext.REFERRAL, connection.getReferral().value().toLowerCase()); } else { props.setProperty(DirContext.REFERRAL, LdapReferralType.IGNORE.value().toLowerCase()); } if (connection.getDerefAliases() != null) { props.setProperty("java.naming.ldap.derefAliases", getDerefJndiValue(connection.getDerefAliases())); } else { props.setProperty("java.naming.ldap.derefAliases", getDerefJndiValue(LdapDerefAliasesType.NEVER)); } if (connection.getBinaryAttributes() != null) { props.setProperty("java.naming.ldap.attributes.binary", StringUtils.join(connection.getBinaryAttributes().getString(), " ")); } if (connection.getPageSize() != null) { props.setProperty("java.naming.ldap.pageSize", "" + connection.getPageSize()); } if (connection.getSortedBy() != null) { props.setProperty("java.naming.ldap.sortedBy", connection.getSortedBy()); } props.setProperty("java.naming.ldap.version", (connection.getVersion() == LdapVersionType.VERSION_2 ? "2" : "3")); if (connection.isRecursiveDelete() != null) { props.setProperty("java.naming.recursivedelete", Boolean.toString(connection.isRecursiveDelete())); } return props; }
From source file:org.marketcetera.modules.remote.receiver.ClientLoginModuleTest.java
/** * Attempt login and test for failure / success conditions * * @param name the user name// w w w .j a v a 2 s .com * @param password the password * @param failure expected failure * @param failureMsg expected failure message * * @return the failure exception if any * * @throws Exception if there was unexpected failure */ private LoginException attemptLogin(String name, char[] password, Class<? extends LoginException> failure, String failureMsg) throws Exception { MockCallbackHandler ch = null; loginContext = null; try { ch = new MockCallbackHandler(name, password); loginContext = new LoginContext(JaasConfiguration.REMOTING_LOGIN_DOMAIN, ch); loginContext.login(); assertNull("Expected failure:" + failure + failureMsg, failure); //verify that the appropriate principals are set in the subject assertTrue(loginContext.getSubject().getPrincipals().toString(), loginContext.getSubject().getPrincipals().contains(new UserPrincipal(getTestUsername()))); } catch (LoginException e) { assertNotNull("Unexpected failure:" + e, failure); assertTrue("Expected:" + failure + ":Actual:" + e.getClass().getName() + e.toString(), failure.isInstance(e)); if (failureMsg != null) { assertEquals(failureMsg, e.getMessage()); } assertNotNull(loginContext); //verify that the appropriate principals are not set in the subject if (loginContext.getSubject() != null && loginContext.getSubject().getPrincipals() != null) { assertFalse(loginContext.getSubject().getPrincipals().toString(), loginContext.getSubject().getPrincipals().contains(new UserPrincipal(getTestUsername()))); } assertEquals(2, ch.getNumCallbacks()); //These values are only set if call back handler doesn't throw //exceptions if (callbackException == null && !doNotHandleCallbacks) { assertEquals(Messages.PROMPT_USERNAME.getText(), ch.getNamePrompt()); assertEquals(Messages.PROMPT_PASSWORD.getText(), ch.getPasswordPrompt()); assertNull(ch.getDefaultName()); } return e; } return null; }
From source file:org.mc4j.ems.impl.jmx.connection.support.providers.JBossConnectionProvider.java
private void initJaasLoginContext() throws LoginException { Configuration jaasConfig = new JBossConfiguration(); Configuration.setConfiguration(jaasConfig); JBossCallbackHandler jaasCallbackHandler = new JBossCallbackHandler(this.connectionSettings.getPrincipal(), this.connectionSettings.getCredentials()); this.loginContext = new LoginContext(JBossConfiguration.JBOSS_ENTRY_NAME, jaasCallbackHandler); }
From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java
protected Principal doAuthenticate(CachableUserIdentificationInfo cachableUserIdent, HttpServletRequest httpRequest) { LoginContext loginContext;/* w w w . ja v a 2s .c om*/ try { CallbackHandler handler = service.getCallbackHandler(cachableUserIdent.getUserInfo()); loginContext = new LoginContext(securityDomain, handler); if (isLoginSynchronized()) { synchronized (NuxeoAuthenticationFilter.class) { loginContext.login(); } } else { loginContext.login(); } Principal principal = (Principal) loginContext.getSubject().getPrincipals().toArray()[0]; cachableUserIdent.setPrincipal(principal); cachableUserIdent.setAlreadyAuthenticated(true); // re-set the userName since for some SSO based on token, // the userName is not known before login is completed cachableUserIdent.getUserInfo().setUserName(principal.getName()); logAuthenticationAttempt(cachableUserIdent.getUserInfo(), true); } catch (LoginException e) { log.info("Login failed for " + cachableUserIdent.getUserInfo().getUserName()); logAuthenticationAttempt(cachableUserIdent.getUserInfo(), false); Throwable cause = e.getCause(); if (cause instanceof DirectoryException) { Throwable rootCause = ExceptionUtils.getRootCause(cause); if (rootCause instanceof NamingException && rootCause.getMessage().contains("LDAP response read timed out") || rootCause instanceof SocketException) { httpRequest.setAttribute(LOGIN_STATUS_CODE, HttpServletResponse.SC_GATEWAY_TIMEOUT); } return DIRECTORY_ERROR_PRINCIPAL; } return null; } // store login context for the time of the request // TODO logincontext is also stored in cachableUserIdent - it is really // needed to store it?? httpRequest.setAttribute(LOGINCONTEXT_KEY, loginContext); // store user ident cachableUserIdent.setLoginContext(loginContext); boolean createSession = needSessionSaving(cachableUserIdent.getUserInfo()); HttpSession session = httpRequest.getSession(createSession); if (session != null) { session.setAttribute(USERIDENT_KEY, cachableUserIdent); } service.onAuthenticatedSessionCreated(httpRequest, session, cachableUserIdent); return cachableUserIdent.getPrincipal(); }
From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java
/** * Does a forced login as the given user. Bypasses all authentication checks. * * @param username the user name//from ww w.j a v a 2s. c om * @return the login context, which MUST be used for logout in a {@code finally} block * @throws LoginException */ public static LoginContext loginAs(String username) throws LoginException { UserIdentificationInfo userIdent = new UserIdentificationInfo(username, ""); userIdent.setLoginPluginName(TrustingLoginPlugin.NAME); PluggableAuthenticationService authService = (PluggableAuthenticationService) Framework.getRuntime() .getComponent(PluggableAuthenticationService.NAME); CallbackHandler callbackHandler; if (authService != null) { callbackHandler = authService.getCallbackHandler(userIdent); } else { callbackHandler = new UserIdentificationInfoCallbackHandler(userIdent); } LoginContext loginContext = new LoginContext(LOGIN_DOMAIN, callbackHandler); if (isLoginSynchronized()) { synchronized (NuxeoAuthenticationFilter.class) { loginContext.login(); } } else { loginContext.login(); } return loginContext; }
From source file:org.processbase.ui.core.BPMModule.java
public User authUserWithJaas(String username, String password) { try {// w w w . java 2 s . c om LoginContext ctx = new LoginContext("SmartBPM", new ProcessbaseAuthCallbackHandler(username, password)); ctx.login(); //ctx.getSubject().getPrincipals(); return null; } catch (Exception e) { logger.error("AuthUser", e); } return null; }
From source file:org.qualipso.factory.ui.core.browser.server.BrowserServletImpl.java
private void login() { String username = null;//from w w w .j a v a 2 s. c om String password = null; // check to see if there's a session existing HttpSession session = getThreadLocalRequest().getSession(false); if (session != null) { username = (String) session.getAttribute(USERNAME_SESSION_ATTRIBUTE); password = (String) session.getAttribute(PASSWORD_SESSION_ATTRIBUTE); logger.info("Getting log info from cookie : login for user " + username); } // // DEBUG // else { // logger.info("Using debug mode, login as root"); // username = "root"; // password = "tagada"; // } // create the login context if ((username != null) && (password != null)) { try { loginContext = new LoginContext("qualipso", new UsernamePasswordHandler(username, password)); loginContext.login(); } catch (LoginException le) { logger.error("Cannot manage to use the login context. Caused by: ", le); } } }
From source file:org.qualipso.factory.ui.core.login.server.LoginServletImpl.java
/** * Try to log in the factory using the given username and password. * //from w ww.j ava 2 s. c o m * @see org.qualipso.factory.ui.core.login.client.LoginServlet#login(java.lang.String, java.lang.String) * * @param username * the username * @param password * the password * @return true if the user information allow him to log in, false otherwise */ public Boolean login(String username, String password) { logger.info("User " + username + " trying to log on the factory..."); // clean old login session if necessary HttpSession session = getThreadLocalRequest().getSession(false); if (session != null) { session.removeAttribute(USERNAME_SESSION_ATTRIBUTE); session.removeAttribute(PASSWORD_SESSION_ATTRIBUTE); session.invalidate(); } // get the naming context for lookup factory services final Context namingContext; try { final Properties properties = new Properties(); properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); properties.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); properties.put("java.naming.provider.url", "localhost:1099"); namingContext = new InitialContext(properties); } catch (NamingException ne) { logger.error("Cannot manage to access Factory through naming. Caused by: ", ne); return false; } // check the application context to see if the bootstrap has already been done // thanks to Jerome for this piece of code String bootstrapped = (String) getThreadLocalRequest().getSession().getServletContext() .getAttribute(BOOTSTRAPPED_FLAG); if (bootstrapped == null) { logger.info("No bootstrap flag found in the application context."); logger.info("Bootstrap of the factory is needed, in progress...."); try { BootstrapService bootstrap = (BootstrapService) namingContext .lookup(FactoryNamingConvention.getJNDINameForService(BootstrapService.SERVICE_NAME)); bootstrap.bootstrap(); getThreadLocalRequest().getSession().getServletContext().setAttribute(BOOTSTRAPPED_FLAG, BOOTSTRAPPED_FLAG); logger.info("Bootstrap of the factory done."); } catch (NamingException ne) { logger.error("Cannot manage to access Factory bootstrap service. Caused by: ", ne); return false; } catch (BootstrapServiceException bse) { logger.error("Cannot manage to call Factory bootstrap service. Caused by: ", bse); return false; } } else { logger.info("Bootstrap flag found in the application context, no need to bootstrap."); } // get the membership service final MembershipService membership; try { membership = (MembershipService) namingContext .lookup(FactoryNamingConvention.getJNDINameForService(MembershipService.SERVICE_NAME)); } catch (NamingException ne) { logger.error("Cannot manage to access Factory membership service. Caused by: ", ne); return false; } // create a login context LoginContext loginContext; try { loginContext = new LoginContext("qualipso", new UsernamePasswordHandler(username, password)); loginContext.login(); } catch (LoginException le) { logger.error("Cannot manage to use the login context. Caused by: ", le); return false; } // test if the login context is valid by trying to call the membership service final String profilePath; try { profilePath = membership.getProfilePathForConnectedIdentifier(); logger.info("Profile path for user " + username + ": " + profilePath); } catch (EJBAccessException no) { // login is invalid logger.info("Login failed for user " + username); return false; } // if we're here, the login is valid. Put it in the session. session = getThreadLocalRequest().getSession(); session.setAttribute(USERNAME_SESSION_ATTRIBUTE, username); session.setAttribute(PASSWORD_SESSION_ATTRIBUTE, password); logger.info("User " + username + " logged in, with profile path " + profilePath); // log out try { loginContext.logout(); } catch (LoginException le) { // just log, don't do anything else logger.error("Problem logging out after testing correct login. Caused by: ", le); } return true; }
From source file:org.qualipso.funkyfactory.test.clock.functionnal.ClockServiceFunctionalTest.java
/** * Test the getTime ClockService authentified *///w w w . j a v a2 s .c o m @Test public void testGetTimeAuthentified() { logger.debug("Testing ClockService authentified"); try { UsernamePasswordHandler uph = new UsernamePasswordHandler("kermit", "thefrog"); LoginContext loginContext = new LoginContext("tests", uph); loginContext.login(); messageTest(); loginContext.logout(); } catch (LoginException e) { logger.error("Problem when loggin in"); logger.error(e.getMessage(), e); fail(e.getMessage()); } catch (NamingException e) { logger.error("Problem when doing the service lookup"); logger.error(e.getMessage(), e); fail(e.getMessage()); } catch (ClockServiceException e) { logger.error("Problem when calling the service"); logger.error(e.getMessage(), e); fail(e.getMessage()); } }
From source file:org.qualipso.funkyfactory.ui.login.server.LoginServletImpl.java
public Boolean login(String username, String password) { logger.info("login: USERNAME=" + username + " --- PASSWORD=" + password); UsernamePasswordHandler uph = new UsernamePasswordHandler(username, password); LoginContext loginContext;// w ww .j ava2 s. c om try { loginContext = new LoginContext("client-login", uph); loginContext.login(); } catch (LoginException e) { logger.info("ca pete dans le login"); e.printStackTrace(); } try { logger.info("Profile Path" + membership.getProfilePathForConnectedIdentifier()); } catch (MembershipServiceException e) { logger.info("ca pete dans le membership"); e.printStackTrace(); } catch (EJBAccessException e1) { logger.info("Thou Shalt Not Pass !!!"); return new Boolean(false); } HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); session.setAttribute("username", username); session.setAttribute("password", password); logger.info("session stored: " + username + " " + password); String sessionid = session.getId(); logger.info("login session: " + sessionid); Cookie ssocookie = new Cookie("SSOSESSIONID", sessionid); ssocookie.setPath("/"); this.getThreadLocalResponse().addCookie(ssocookie); storeDataInContext(sessionid, username, password); return true; }