Java Code Examples for javax.security.auth.login.LoginException

The following examples show how to use javax.security.auth.login.LoginException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: jdk8u-dev-jdk   Source File: OnlyDesLogin.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        OneKDC kdc = new OneKDC(null);
        kdc.writeJAASConf();

        KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
                "default_tkt_enctypes=des-cbc-md5",
                "default_tgs_enctypes=des-cbc-md5",
                "permitted_enctypes=des-cbc-md5");
        Config.refresh();

        try {
            Context.fromJAAS("client");
            throw new Exception("What?");
        } catch (LoginException le) {
            // This is OK
        }
    }
 
Example 2
Source Project: unitime   Source File: LdapAuthenticateModule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Commit phase of login
 */
public boolean commit() throws LoginException {
	if (isAuthSucceeded()) { // Check if authentication succeeded

		// External UID must exist in order to get manager info
		if (iExternalUid == null || iExternalUid.trim().length() == 0)
			throw new LoginException("External UID not found");

		getSubject().getPrincipals().add(new AuthenticatedUser(getUser(), iExternalUid));

		setCommitSucceeded(true);
		return true;
	} else { // Authentication failed - do not commit
		reset();
		return false;
	}
}
 
Example 3
Source Project: big-c   Source File: TestSecureRMRegistryOperations.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the RM registry operations as the current user
 * @return the service
 * @throws LoginException
 * @throws FileNotFoundException
 */
public RMRegistryOperationsService startRMRegistryOperations() throws
    LoginException, IOException, InterruptedException {
  // kerberos
  secureConf.set(KEY_REGISTRY_CLIENT_AUTH,
      REGISTRY_CLIENT_AUTH_KERBEROS);
  secureConf.set(KEY_REGISTRY_CLIENT_JAAS_CONTEXT, ZOOKEEPER_CLIENT_CONTEXT);

  RMRegistryOperationsService registryOperations = zookeeperUGI.doAs(
      new PrivilegedExceptionAction<RMRegistryOperationsService>() {
        @Override
        public RMRegistryOperationsService run() throws Exception {
          RMRegistryOperationsService operations
              = new RMRegistryOperationsService("rmregistry", secureZK);
          addToTeardown(operations);
          operations.init(secureConf);
          LOG.info(operations.bindingDiagnosticDetails());
          operations.start();
          return operations;
        }
      });

  return registryOperations;
}
 
Example 4
Source Project: nifi   Source File: DBCPConnectionPool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Shutdown pool, close all open connections.
 * If a principal is authenticated with a KDC, that principal is logged out.
 *
 * If a @{@link LoginException} occurs while attempting to log out the @{@link org.apache.nifi.security.krb.KerberosUser},
 * an attempt will still be made to shut down the pool and close open connections.
 *
 * @throws SQLException if there is an error while closing open connections
 * @throws LoginException if there is an error during the principal log out, and will only be thrown if there was
 * no exception while closing open connections
 */
@OnDisabled
public void shutdown() throws SQLException, LoginException {
    try {
        if (kerberosUser != null) {
            kerberosUser.logout();
        }
    } finally {
        kerberosUser = null;
        try {
            if (dataSource != null) {
                dataSource.close();
            }
        } finally {
            dataSource = null;
        }
    }
}
 
Example 5
Source Project: openjdk-8-source   Source File: Krb5Util.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves the ServiceCreds for the specified server principal from
 * the Subject in the specified AccessControlContext. If not found, and if
 * useSubjectCredsOnly is false, then obtain from a LoginContext.
 *
 * NOTE: This method is also used by JSSE Kerberos Cipher Suites
 */
public static ServiceCreds getServiceCreds(GSSCaller caller,
    String serverPrincipal, AccessControlContext acc)
            throws LoginException {

    Subject accSubj = Subject.getSubject(acc);
    ServiceCreds sc = null;
    if (accSubj != null) {
        sc = ServiceCreds.getInstance(accSubj, serverPrincipal);
    }
    if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
        sc = ServiceCreds.getInstance(subject, serverPrincipal);
    }
    return sc;
}
 
Example 6
Source Project: jdk8u-jdk   Source File: OnlyDesLogin.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        OneKDC kdc = new OneKDC(null);
        kdc.writeJAASConf();

        KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
                "default_tkt_enctypes=des-cbc-md5",
                "default_tgs_enctypes=des-cbc-md5",
                "permitted_enctypes=des-cbc-md5");
        Config.refresh();

        try {
            Context.fromJAAS("client");
            throw new Exception("What?");
        } catch (LoginException le) {
            // This is OK
        }
    }
 
Example 7
Source Project: nifi   Source File: PutHiveStreaming.java    License: Apache License 2.0 6 votes vote down vote up
UserGroupInformation getUgi() {
    getLogger().trace("getting UGI instance");
    if (kerberosUserReference.get() != null) {
        // if there's a KerberosUser associated with this UGI, check the TGT and relogin if it is close to expiring
        KerberosUser kerberosUser = kerberosUserReference.get();
        getLogger().debug("kerberosUser is " + kerberosUser);
        try {
            getLogger().debug("checking TGT on kerberosUser [{}]", new Object[] {kerberosUser});
            kerberosUser.checkTGTAndRelogin();
        } catch (LoginException e) {
            throw new ProcessException("Unable to relogin with kerberos credentials for " + kerberosUser.getPrincipal(), e);
        }
    } else {
        getLogger().debug("kerberosUser was null, will not refresh TGT with KerberosUser");
    }
    return ugi;
}
 
Example 8
Source Project: hottub   Source File: LCTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    LCTest.logAction("commit");
    if (succeeded == false) {
        return false;
    }
    userPrincipal = new UnixPrincipal(username);
    final Subject s = subject;
    final UnixPrincipal up = userPrincipal;
    java.security.AccessController.doPrivileged
            ((java.security.PrivilegedAction) () -> {
                if (!s.getPrincipals().contains(up)) {
                    s.getPrincipals().add(up);
                }
                return null;
            });
    password = null;
    commitSucceeded = true;
    return true;
}
 
Example 9
@Override
public String login(String username, String password) throws LoginException, SchedulerRestException {
    try {
        if ((username == null) || (password == null)) {
            throw new LoginException("Empty login/password");
        }
        Session session = sessionStore.create(username);
        session.connectToScheduler(new CredData(username, password));
        logger.info("Binding user " + username + " to session " + session.getSessionId());

        return session.getSessionId();
    } catch (ActiveObjectCreationException | SchedulerException | NodeException e) {
        throw new SchedulerRestException(e);
    }
}
 
Example 10
Source Project: openjdk-jdk9   Source File: LCTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean abort() throws LoginException {
    LCTest.logAction("abort");
    if (succeeded == false) {
        return false;
    }
    clearState();
    return true;
}
 
Example 11
Source Project: mobi   Source File: TokenLoginModule.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    if (this.userId != null) {
        this.subject.getPrincipals().add(new UserPrincipal(this.userId));
        return true;
    }

    return false;
}
 
Example 12
Source Project: tomee   Source File: TomcatSecurityService.java    License: Apache License 2.0 5 votes vote down vote up
public UUID login(final String realmName, final String username, final String password) throws LoginException {
    final Realm realm = findRealm(realmName);
    if (realm == null) {
        throw new LoginException("No Tomcat realm available");
    }

    final Principal principal = realm.authenticate(username, password);
    if (principal == null) {
        throw new CredentialNotFoundException(username);
    }

    final Subject subject = createSubject(realm, principal);
    return registerSubject(subject);
}
 
Example 13
Source Project: datacollector   Source File: LdapLoginModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean abort() throws LoginException
{
  if (conn != null && conn.isOpen()) {
    conn.close();
  }
  return super.abort();
}
 
Example 14
Source Project: Bats   Source File: PlainFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UserGroupInformation createAndLoginUser(Map<String, ?> properties) throws IOException {
  final Configuration conf = new SecurityConfiguration();
  UserGroupInformation.setConfiguration(conf);
  try {
    return UserGroupInformation.getCurrentUser();
  } catch (final IOException e) {
    logger.debug("Login failed.", e);
    final Throwable cause = e.getCause();
    if (cause instanceof LoginException) {
      throw new SaslException("Failed to login.", cause);
    }
    throw new SaslException("Unexpected failure trying to login. ", cause);
  }
}
 
Example 15
@Override
public boolean commit() throws LoginException {
    out.println("Commit of AbstractLoginModule is called");
    out.println(name + ":commit:PASS");
    return true;

}
 
Example 16
/**
 * Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
 *
 * @param username Username that was successfully authenticated which is used for principal ID when
 *                 {@link #setPrincipalIdAttribute(String)} is not specified.
 * @param ldapEntry LDAP entry that may contain principal attributes.
 *
 * @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
 *
 * @throws LoginException On security policy errors related to principal creation.
 */
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
    final String id;
    if (this.principalIdAttribute != null) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {
            throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
        }
        if (principalAttr.size() > 1) {
            if (this.allowMultiplePrincipalAttributeValues) {
                logger.warn(
                        "Found multiple values for principal ID attribute: {}. Using first value={}.",
                        principalAttr,
                        principalAttr.getStringValue());
            } else {
                throw new LoginException("Multiple principal values not allowed: " + principalAttr);
            }
        }
        id = principalAttr.getStringValue();
    } else {
        id = username;
    }
    final Map<String, Object> attributeMap = new LinkedHashMap<String, Object>(this.principalAttributeMap.size());
    for (String ldapAttrName : this.principalAttributeMap.keySet()) {
        final LdapAttribute attr = ldapEntry.getAttribute(ldapAttrName);
        if (attr != null) {
            logger.debug("Found principal attribute: {}", attr);
            final String principalAttrName = this.principalAttributeMap.get(ldapAttrName);
            if (attr.size() > 1) {
                attributeMap.put(principalAttrName, attr.getStringValues());
            } else {
                attributeMap.put(principalAttrName, attr.getStringValue());
            }
        }
    }
    return new SimplePrincipal(id, attributeMap);
}
 
Example 17
@Override
public Set<String> resolve(org.taktik.icure.dto.filter.service.ServiceByHcPartyTagCodeDateFilter filter, Filters context) {
	try {
           String hcPartyId = filter.getHealthcarePartyId() != null ? filter.getHealthcarePartyId() : getLoggedHealthCarePartyId();
           HashSet<String> ids = null;

           String patientSFK = filter.getPatientSecretForeignKey();
           List<String> patientSFKList = patientSFK != null ? Arrays.asList(patientSFK) : null;

           if (filter.getTagType() != null && filter.getTagCode() != null) {
               ids = new HashSet<>(contactLogic.listServiceIdsByTag(
                       hcPartyId,
                       patientSFKList, filter.getTagType(),
                       filter.getTagCode(), filter.getStartValueDate(), filter.getEndValueDate()
               ));
           }

           if (filter.getCodeType() != null && filter.getCodeCode() != null) {
               List<String> byCode = contactLogic.listServiceIdsByCode(
                       hcPartyId,
                       patientSFKList, filter.getCodeType(),
                       filter.getCodeCode(), filter.getStartValueDate(), filter.getEndValueDate()
               );
               if (ids==null) { ids = new HashSet<>(byCode); } else { ids.retainAll(byCode); }
           }

           return ids != null ? ids : new HashSet<>();
	} catch (LoginException e) {
		throw new IllegalArgumentException(e);
	}
}
 
Example 18
Source Project: tomcatsrc   Source File: JAASMemoryLoginModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Log out this user.
 *
 * @return <code>true</code> in all cases because the
 *  <code>LoginModule</code> should not be ignored
 *
 * @exception LoginException if logging out failed
 */
@Override
public boolean logout() throws LoginException {

    subject.getPrincipals().remove(principal);
    committed = false;
    principal = null;
    return (true);

}
 
Example 19
Source Project: pentaho-kettle   Source File: KerberosUtil.java    License: Apache License 2.0 5 votes vote down vote up
public LoginContext getLoginContextFromKeytab( String principal, String keytab ) throws LoginException {
  Map<String, String> keytabConfig = new HashMap<String, String>( LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB );
  keytabConfig.put( "keyTab", keytab );
  keytabConfig.put( "principal", principal );

  // Create the configuration and from them, a new login context
  AppConfigurationEntry config =
      new AppConfigurationEntry( Krb5LoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, keytabConfig );
  AppConfigurationEntry[] configEntries = new AppConfigurationEntry[] { config };
  Subject subject = new Subject();
  return new LoginContext( KERBEROS_APP_NAME, subject, null, new PentahoLoginConfiguration( configEntries ) );
}
 
Example 20
public static void main(String[] args) throws Exception {

        new OneKDC(null).writeJAASConf();

        // KDC would save ccache for client
        System.setProperty("test.kdc.save.ccache", "cache.here");
        try (FileOutputStream fos = new FileOutputStream(OneKDC.JAAS_CONF)) {
            fos.write((
                "me {\n" +
                "    com.sun.security.auth.module.Krb5LoginModule required\n" +
                "    principal=\"" + OneKDC.USER + "\"\n" +
                "    useTicketCache=true\n" +
                "    ticketCache=cache.here\n" +
                "    isInitiator=true\n" +
                "    storeKey=true;\n};\n"
                ).getBytes());
        }

        // The first login will use default callback and succeed
        Context.fromJAAS("me");

        // The second login uses ccache and won't be able to store the keys
        try {
            Context.fromJAAS("me");
            throw new Exception("Should fail");
        } catch (LoginException le) {
            if (le.getMessage().indexOf("NullPointerException") >= 0
                    || le.getCause() instanceof NullPointerException) {
                throw new Exception("NPE");
            }
        }
    }
 
Example 21
/**
 * Overriding to allow for role discovery based on text files.
 *
 * @param username The name of the user being examined. This is the same
 *                 name returned by getUserNameForCertificates.
 * @return A Set of name Strings for roles this user belongs to.
 * @throws LoginException Thrown if unable to find role definition file.
 */
@Override
protected Set<String> getUserRoles(String username) throws LoginException {
   Set<String> userRoles = rolesByUser.get(username);
   if (userRoles == null) {
      userRoles = Collections.emptySet();
   }

   return userRoles;
}
 
Example 22
Source Project: icure-backend   Source File: PatientFacade.java    License: GNU General Public License v2.0 5 votes vote down vote up
@ApiOperation(
		value = "Get ids of patients matching the provided filter for the current user (HcParty) ",
		response = String.class,
		responseContainer = "Array",
		httpMethod = "POST"
)
@POST
@Path("/match")
public List<String> matchBy(Filter filter) throws LoginException {
	return new ArrayList<>(filters.resolve(filter));
}
 
Example 23
Source Project: openjdk-8   Source File: Krb5Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the caller's Subject, or Subject obtained by logging in
 * via the specified caller.
 *
 * Caller must have permission to:
 *    - access the Subject
 *    - create LoginContext
 *    - read the auth.login.defaultCallbackHandler security property
 *
 * NOTE: This method is used by JSSE Kerberos Cipher Suites
 */
public static Subject getSubject(GSSCaller caller,
    AccessControlContext acc) throws LoginException {

    // Try to get the Subject from acc
    Subject subject = Subject.getSubject(acc);

    // Try to get Subject obtained from GSSUtil
    if (subject == null && !GSSUtil.useSubjectCredsOnly(caller)) {
        subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
    }
    return subject;
}
 
Example 24
/**
 * Returns true if user was successfully authenticated against Kerberos
 *
 * @param username username without Kerberos realm attached or with correct realm attached
 * @param password kerberos password
 * @return  true if user was successfully authenticated
 */
public boolean validUser(String username, String password) {
    try {
        authenticateSubject(username, password);
        logoutSubject();
        return true;
    } catch (LoginException le) {
        checkKerberosServerAvailable(le);

        logger.debug("Failed to authenticate user " + username, le);
        return false;
    }
}
 
Example 25
Source Project: jdk8u-jdk   Source File: BadKdc.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void go(String... expected)
        throws Exception {
    try {
        go0(expected);
    } catch (BindException be) {
        System.out.println("The random port is used by another process");
    } catch (LoginException le) {
        Throwable cause = le.getCause();
        if (cause instanceof Asn1Exception) {
            System.out.println("Bad packet possibly from another process");
            return;
        }
        throw le;
    }
}
 
Example 26
Source Project: herddb   Source File: SaslNettyServer.java    License: Apache License 2.0 5 votes vote down vote up
private Subject loginServer() throws SaslException, PrivilegedActionException, LoginException {
    AppConfigurationEntry[] entries = Configuration.getConfiguration().getAppConfigurationEntry(JASS_SERVER_SECTION);
    if (entries == null) {
        return null;
    }
    LoginContext loginContext = new LoginContext(JASS_SERVER_SECTION, new ClientCallbackHandler(null));
    loginContext.login();
    return loginContext.getSubject();

}
 
Example 27
Source Project: TencentKona-8   Source File: LCTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean abort() throws LoginException {
    LCTest.logAction("abort");
    if (succeeded == false) {
        return false;
    }
    clearState();
    return true;
}
 
Example 28
Source Project: hottub   Source File: SharedState.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws LoginException {
    System.setProperty("java.security.auth.login.config",
            System.getProperty("test.src")
                    + System.getProperty("file.separator")
                    + "shared.config");

    new LoginContext("SharedState").login();
}
 
Example 29
private void checkAlias() throws LoginException {
    if (keyStoreAlias == null) {
        throw new LoginException
            ("Need to specify an alias option to use " +
            "KeyStoreLoginModule non-interactively.");
    }
}
 
Example 30
Source Project: datacollector   Source File: LdapLoginModule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean commit() throws LoginException
{
  if (conn != null && conn.isOpen()) {
    conn.close();
  }
  return super.commit();
}