javax.security.auth.login.LoginException Java Examples

The following examples show how to use javax.security.auth.login.LoginException. 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 check out the related API usage on the sidebar.
Example #1
Source File: PutHiveStreaming.java    From nifi with 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 #2
Source File: DBCPConnectionPool.java    From nifi with 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 #3
Source File: OnlyDesLogin.java    From jdk8u-dev-jdk with 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 #4
Source File: LdapAuthenticateModule.java    From unitime with 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 #5
Source File: TestSecureRMRegistryOperations.java    From big-c with 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 #6
Source File: OnlyDesLogin.java    From jdk8u-jdk with 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 File: LCTest.java    From hottub with 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 #8
Source File: Krb5Util.java    From openjdk-8-source with 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 #9
Source File: UnboundSSLMultipleKeys.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args)
        throws IOException, NoSuchAlgorithmException, LoginException,
        PrivilegedActionException, InterruptedException {
    Security.setProperty("jdk.tls.disabledAlgorithms", "");
    UnboundSSLMultipleKeys test = new UnboundSSLMultipleKeys();
    test.start(args[0], args[1]);
}
 
Example #10
Source File: CustomLoginModule.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean commit() throws LoginException {
    if (loginSucceeded) {
        // add a Principal to the Subject
        Principal principal = new TestPrincipal(username);
        if (!subject.getPrincipals().contains(principal)) {
            subject.getPrincipals().add(principal);
        }
        return true;
    }

    return false;
}
 
Example #11
Source File: TextFileCertificateLoginModule.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #12
Source File: UseCacheAndStoreKey.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #13
Source File: UserDomainLoginTestCase.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testOtherDomainFail() throws Exception {
    LoginContextBuilder builder = new LoginContextBuilder(Type.AUTHENTICATION);
    LoginContext loginContext = builder.username("user2").password("appl-pa$$wrd2".toCharArray()).build();
    try {
        loginContext.login();
        Assert.fail("LoginException expected");
    } catch (LoginException e) {
        // expected
    }
}
 
Example #14
Source File: KerberosUtil.java    From pentaho-kettle with 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 #15
Source File: JAASMemoryLoginModule.java    From tomcatsrc with 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 #16
Source File: ServiceByHcPartyTagCodeDateFilter.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@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 #17
Source File: LdapLoginModule.java    From datacollector with 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 #18
Source File: Unreachable.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    File f = new File(
            System.getProperty("test.src", "."), "unreachable.krb5.conf");
    System.setProperty("java.security.krb5.conf", f.getPath());
    Config.refresh();

    // If PortUnreachableException is not received, the login will consume
    // about 3*3*30 seconds and the test will timeout.
    try {
        Context.fromUserPass("name", "pass".toCharArray(), true);
    } catch (LoginException le) {
        // This is OK
    }
}
 
Example #19
Source File: PatientFacade.java    From icure-backend with 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 #20
Source File: LCTest.java    From jdk8u_jdk with 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 #21
Source File: Krb5Util.java    From openjdk-8 with 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 #22
Source File: UserBeanTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoginForClosedMarketplace() throws LoginException, ValidationException, OperationNotPermittedException, ObjectNotFoundException, OrganizationRemovedException {
    //given
    doReturn(false).when(userBean).isServiceProvider();
    VOUser mockUser = mock(VOUser.class);
    doReturn(mockUser).when(idServiceMock).getUser(any(VOUser.class));
    doReturn(false).when(marketplaceService).doesOrganizationHaveAccessMarketplace(anyString(), anyString());
    userBean.setUserId("ID");
    //when
    userBean.login();
    //then
    verify(requestMock, times(1)).setAttribute(Constants.REQ_ATTR_ERROR_KEY,
            BaseBean.ERROR_LOGIN_TO_CLOSED_MARKETPLACE);
}
 
Example #23
Source File: KerberosUsernamePasswordAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: BadKdc.java    From jdk8u-jdk with 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 #25
Source File: SaslNettyServer.java    From herddb with 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 #26
Source File: LCTest.java    From TencentKona-8 with 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 #27
Source File: SharedState.java    From hottub with 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 #28
Source File: KeyStoreLoginModule.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void checkAlias() throws LoginException {
    if (keyStoreAlias == null) {
        throw new LoginException
            ("Need to specify an alias option to use " +
            "KeyStoreLoginModule non-interactively.");
    }
}
 
Example #29
Source File: LdapLoginModule.java    From datacollector with 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();
}
 
Example #30
Source File: KerberosUserIT.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testKeytabUserSuccessfulLoginAndLogout() throws LoginException {
    // perform login for user1
    final KerberosUser user1 = new KerberosKeytabUser(principal1.getName(), principal1KeytabFile.getAbsolutePath());
    user1.login();

    // perform login for user2
    final KerberosUser user2 = new KerberosKeytabUser(principal2.getName(), principal2KeytabFile.getAbsolutePath());
    user2.login();

    // verify user1 Subject only has user1 principal
    final Subject user1Subject = ((KerberosKeytabUser) user1).getSubject();
    final Set<Principal> user1SubjectPrincipals = user1Subject.getPrincipals();
    assertEquals(1, user1SubjectPrincipals.size());
    assertEquals(principal1.getName(), user1SubjectPrincipals.iterator().next().getName());

    // verify user2 Subject only has user2 principal
    final Subject user2Subject = ((KerberosKeytabUser) user2).getSubject();
    final Set<Principal> user2SubjectPrincipals = user2Subject.getPrincipals();
    assertEquals(1, user2SubjectPrincipals.size());
    assertEquals(principal2.getName(), user2SubjectPrincipals.iterator().next().getName());

    // call check/relogin and verify neither user performed a relogin
    assertFalse(user1.checkTGTAndRelogin());
    assertFalse(user2.checkTGTAndRelogin());

    // perform logout for both users
    user1.logout();
    user2.logout();

    // verify subjects have no more principals
    assertEquals(0, user1Subject.getPrincipals().size());
    assertEquals(0, user2Subject.getPrincipals().size());
}