List of usage examples for javax.security.auth.login LoginContext login
public void login() throws LoginException
From source file:com.stimulus.archiva.security.realm.ADRealm.java
protected LoginContext kereberosLogin(Config config, ADIdentity identity, String username, String password) throws ArchivaException { logger.debug("kerberosLogin()"); String domain = null;/*from www. j a v a 2 s .c o m*/ String uname = null; LoginContext serverLC = null; BeanCallbackHandler beanCallbackHandler = null; String kdcAddress = identity.getKDCAddress(); if (username.length() < 1) throw new ArchivaException("A service account login name must be specified.", logger); if (password.length() < 1) throw new ArchivaException("A service account login password must be specified.", logger); int at = username.lastIndexOf('@'); if (at == -1) throw new ArchivaException( "The service account login name must be in the format username@company.local.", logger); uname = username.substring(0, at).toLowerCase(Locale.ENGLISH); domain = username.substring(at + 1).toUpperCase(Locale.ENGLISH); logger.debug("kerberosLogin() {domain='" + domain + "', uname='" + username + "',kdcAddress='" + kdcAddress + "'}"); String confFile = Config.getFileSystem().getConfigurationPath() + File.separatorChar + "login.conf"; String krbFile = Config.getFileSystem().getConfigurationPath() + File.separatorChar + "krb5.conf"; beanCallbackHandler = new BeanCallbackHandler(uname, password); if (!new File(krbFile).exists()) { System.setProperty("java.security.krb5.realm", domain); System.setProperty("java.security.krb5.kdc", kdcAddress); if (logger.isDebugEnabled()) System.setProperty("sun.security.krb5.debug", "true"); } else { System.setProperty("java.security.krb5.conf", krbFile); } System.setProperty("java.security.auth.login.config", confFile); try { serverLC = new LoginContext(confName, beanCallbackHandler); serverLC.login(); } catch (Exception e) { throw new ArchivaException("failed to login using kerberos server. " + e.getMessage() + " {realm='" + domain + "',kdcAddress='" + kdcAddress + "'}", e, logger); } logger.debug("kerberosLogin() end"); return serverLC; }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Re-Login a user in from the ticket cache. This method assumes that login had happened already. The Subject field * of this UserGroupInformation object is updated to have the new credentials. * * @throws IOException on a failure/*from w ww . j av a 2 s .c om*/ */ public synchronized void reloginFromTicketCache() throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKrbTkt) return; LoginContext login = getLogin(); if (login == null) { throw new IOException("login must be done first"); } long now = Time.now(); if (!hasSufficientTimeElapsed(now)) { return; } // register most recent relogin attempt user.setLastLogin(now); try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared login.logout(); //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, getSubject(), new HadoopConfiguration()); if (LOG.isDebugEnabled()) { LOG.debug("Initiating re-login for " + getUserName()); } login.login(); setLogin(login); } catch (LoginException le) { throw new IOException("Login failure for " + getUserName(), le); } }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Re-Login a user in from a keytab file. Loads a user identity from a keytab file and logs them in. They become the * currently logged-in user. This method assumes that {@link #loginUserFromKeytab(String, String)} had happened * already. The Subject field of this UserGroupInformation object is updated to have the new credentials. * * @throws IOException on a failure//from w w w . j a v a2 s . c om */ public synchronized void reloginFromKeytab() throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKeytab) return; long now = Time.now(); if (!shouldRenewImmediatelyForTests && !hasSufficientTimeElapsed(now)) { return; } KerberosTicket tgt = getTGT(); //Return if TGT is valid and is not going to expire soon. if (tgt != null && !shouldRenewImmediatelyForTests && now < getRefreshTime(tgt)) { return; } LoginContext login = getLogin(); if (login == null || keytabFile == null) { throw new IOException("loginUserFromKeyTab must be done first"); } long start = 0; // register most recent relogin attempt user.setLastLogin(now); try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } synchronized (UserGroupInformation.class) { // clear up the kerberos state. But the tokens are not cleared! As per // the Java kerberos login module code, only the kerberos credentials // are cleared login.logout(); // login and also update the subject field of this instance to // have the new credentials (pass it to the LoginContext constructor) login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(), new HadoopConfiguration()); if (LOG.isDebugEnabled()) { LOG.debug("Initiating re-login for " + keytabPrincipal); } start = Time.now(); login.login(); // metrics.loginSuccess.add(Time.now() - start); setLogin(login); } } catch (LoginException le) { if (start > 0) { // metrics.loginFailure.add(Time.now() - start); } throw new IOException("Login failure for " + keytabPrincipal + " from keytab " + keytabFile, le); } }
From source file:nl.nn.adapterframework.util.CredentialFactory.java
/** * return a loginContext, obtained by logging in using the obtained credentials *///from w w w . j a v a 2 s . c o m public LoginContext getLoginContext() throws LoginException { String loginConfig = "ClientContainer"; getCredentialsFromAlias(); log.debug("logging in using context[" + loginConfig + "]"); LoginContext lc = new LoginContext(loginConfig, new loginCallbackHandler()); lc.login(); return lc; }
From source file:nl.nn.adapterframework.util.CredentialFactory.java
protected void getCredentialsFromAlias() { if (!gotCredentials && StringUtils.isNotEmpty(getAlias())) { try {//from ww w . j a v a2 s . c o m Set principals = new HashSet(); Set publicCredentials = new HashSet(); Set privateCredentials = new HashSet(); Principal p = new IbisPrincipal(); principals.add(p); Subject initialSubject = new Subject(false, principals, publicCredentials, privateCredentials); String loginConfiguration = AppConstants.getInstance().getProperty("PrincipalMapping", "DefaultPrincipalMapping"); LoginContext lc = new LoginContext(loginConfiguration, initialSubject, this); lc.login(); Subject s = lc.getSubject(); //showSet(s.getPrincipals(),"principals"); //showSet(s.getPublicCredentials(),"PublicCredentials"); //showSet(s.getPrivateCredentials(),"PrivateCredentials"); //Object pwcred=Subject.doAsPrivileged(s,new PasswordGetter(s),AccessController.getContext()); //Object pwcred=AccessController.doPrivileged(new PasswordGetter(s)); Object pwcred = s.getPrivateCredentials().toArray()[0]; setUsername(ClassUtils.invokeStringGetter(pwcred, "getUserName")); setPassword(invokeCharArrayGetter(pwcred, "getPassword")); gotCredentials = true; } catch (Exception e) { if (!useFallback) { NoSuchElementException nsee = new NoSuchElementException( "cannot obtain credentials from authentication alias [" + getAlias() + "]"); nsee.initCause(e); throw nsee; } log.error("exception obtaining credentials for alias [" + getAlias() + "]", e); String usernameProp = "alias." + getAlias() + ".username"; String passwordProp = "alias." + getAlias() + ".password"; log.info("trying to solve Authentication Alias from application properties [" + usernameProp + "] and [" + passwordProp + "]"); setUsername(AppConstants.getInstance().getProperty(usernameProp, username)); setPassword(AppConstants.getInstance().getProperty(passwordProp, password)); } } }
From source file:org.acegisecurity.providers.jaas.JaasAuthenticationProvider.java
/** * Attempts to login the user given the Authentication objects principal and credential * * @param auth The Authentication object to be authenticated. * * @return The authenticated Authentication object, with it's grantedAuthorities set. * * @throws AuthenticationException This implementation does not handle 'locked' or 'disabled' accounts. This method * only throws a AuthenticationServiceException, with the message of the LoginException that will be * thrown, should the loginContext.login() method fail. */// w w w . j a va2 s.co m public Authentication authenticate(Authentication auth) throws AuthenticationException { if (auth instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth; try { //Create the LoginContext object, and pass our InternallCallbackHandler LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth)); //Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point. loginContext.login(); //create a set to hold the authorities, and add any that have already been applied. Set authorities = new HashSet(); if (request.getAuthorities() != null) { authorities.addAll(Arrays.asList(request.getAuthorities())); } //get the subject principals and pass them to each of the AuthorityGranters Set principals = loginContext.getSubject().getPrincipals(); for (Iterator iterator = principals.iterator(); iterator.hasNext();) { Principal principal = (Principal) iterator.next(); for (int i = 0; i < authorityGranters.length; i++) { AuthorityGranter granter = authorityGranters[i]; Set roles = granter.grant(principal); //If the granter doesn't wish to grant any authorities, it should return null. if ((roles != null) && !roles.isEmpty()) { for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();) { String role = roleIterator.next().toString(); authorities.add(new JaasGrantedAuthority(role, principal)); } } } } //Convert the authorities set back to an array and apply it to the token. JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), request.getCredentials(), (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]), loginContext); //Publish the success event publishSuccessEvent(result); //we're done, return the token. return result; } catch (LoginException loginException) { AcegiSecurityException ase = loginExceptionResolver.resolveException(loginException); publishFailureEvent(request, ase); throw ase; } } return null; }
From source file:org.adeptnet.auth.kerberos.Krb5.java
public String isTicketValid(String spn, byte[] ticket) { checkCreds();// www . j ava 2 s .c o m LoginContext ctx = null; try { if (!config.getKeytab().exists()) { throw new LoginException( String.format("KeyTab does not exist: %s", config.getKeytab().getAbsolutePath())); } final Principal principal = new KerberosPrincipal(spn, KerberosPrincipal.KRB_NT_SRV_INST); Set<Principal> principals = new HashSet<>(); principals.add(principal); final Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>()); ctx = new LoginContext(config.getContextName(), subject, null, getJaasKrb5TicketCfg(spn)); ctx.login(); final Krb5TicketValidateAction validateAction = new Krb5TicketValidateAction(ticket, spn); final String username = Subject.doAs(subject, validateAction); return username; } catch (java.security.PrivilegedActionException | LoginException e) { LOG.fatal(spn, e); } finally { try { if (ctx != null) { ctx.logout(); } } catch (LoginException e2) { LOG.fatal(spn, e2); } } return FAILED; }
From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java
@Test public void testLogin() throws LoginException { LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "secret")); context.login(); Subject subject = context.getSubject(); assertEquals("Should have three principals", 3, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have two group principals", 2, subject.getPrincipals(RolePrincipal.class).size()); context.logout();//from ww w. j av a 2 s . c o m assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); }
From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java
@Test public void testLoginReload() throws Exception { File targetPropDir = new File("target/loginReloadTest"); File usersFile = new File(targetPropDir, "users.properties"); File rolesFile = new File(targetPropDir, "roles.properties"); //Set up initial properties FileUtils.copyFile(new File(getClass().getResource("/users.properties").toURI()), usersFile); FileUtils.copyFile(new File(getClass().getResource("/roles.properties").toURI()), rolesFile); LoginContext context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secret")); context.login(); Subject subject = context.getSubject(); //test initial principals assertEquals("Should have three principals", 3, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have two group principals", 2, subject.getPrincipals(RolePrincipal.class).size()); context.logout();/*w w w . j av a2s . c o m*/ assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); //Modify the file and test that the properties are reloaded Thread.sleep(1000); FileUtils.copyFile(new File(getClass().getResource("/usersReload.properties").toURI()), usersFile); FileUtils.copyFile(new File(getClass().getResource("/rolesReload.properties").toURI()), rolesFile); FileUtils.touch(usersFile); FileUtils.touch(rolesFile); //Use new password to verify users file was reloaded context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secrets")); context.login(); subject = context.getSubject(); //Check that the principals changed assertEquals("Should have three principals", 2, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have one group principals", 1, subject.getPrincipals(RolePrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); }
From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java
@Test public void testBadUseridLogin() throws Exception { LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("BAD", "secret")); try {/* w w w .ja va2 s .c o m*/ context.login(); fail("Should have thrown a FailedLoginException"); } catch (FailedLoginException doNothing) { } }