Example usage for javax.security.auth.login LoginContext login

List of usage examples for javax.security.auth.login LoginContext login

Introduction

In this page you can find the example usage for javax.security.auth.login LoginContext login.

Prototype

public void login() throws LoginException 

Source Link

Document

Perform the authentication.

Usage

From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java

@Test
public void testBadPWLogin() throws Exception {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "BAD"));

    try {/*from w ww .jav  a 2s.  c om*/
        context.login();
        fail("Should have thrown a FailedLoginException");
    } catch (FailedLoginException doNothing) {
    }

}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

@Test
public void testSaslGssapiLdapAuth() throws Exception {

    final Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");

    LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
    loginContext.login();
    try {//from   w w  w. j ava 2 s .  c  o  m
        Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {

            HashSet<String> set = new HashSet<>();

            DirContext ctx = new InitialDirContext(env);
            NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

            while (list.hasMore()) {
                NameClassPair ncp = list.next();
                set.add(ncp.getName());
            }

            Assert.assertTrue(set.contains("uid=first"));
            Assert.assertTrue(set.contains("cn=users"));
            Assert.assertTrue(set.contains("ou=configuration"));
            Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

            ctx.close();
            return null;

        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}

From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java

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(GroupPrincipal.class).size());

    context.logout();/*from  w w w  . j  a va 2s. c om*/

    assertEquals("Should have zero principals", 0, subject.getPrincipals().size());
}

From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java

public void testLoginReload() throws Exception {
    File targetPropDir = new File("target/loginReloadTest");
    File sourcePropDir = new File("src/test/resources");
    File usersFile = new File(targetPropDir, "users.properties");
    File groupsFile = new File(targetPropDir, "groups.properties");

    //Set up initial properties
    FileUtils.copyFile(new File(sourcePropDir, "users.properties"), usersFile);
    FileUtils.copyFile(new File(sourcePropDir, "groups.properties"), groupsFile);

    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(GroupPrincipal.class).size());

    context.logout();// w w  w . j a  v  a2s. co 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(sourcePropDir, "usersReload.properties"), usersFile);
    FileUtils.copyFile(new File(sourcePropDir, "groupsReload.properties"), groupsFile);
    FileUtils.touch(usersFile);
    FileUtils.touch(groupsFile);

    //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(GroupPrincipal.class).size());

    context.logout();

    assertEquals("Should have zero principals", 0, subject.getPrincipals().size());
}

From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java

public void testBadUseridLogin() throws Exception {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("BAD", "secret"));

    try {//from ww  w.j  a  va  2s.co m
        context.login();
        fail("Should have thrown a FailedLoginException");
    } catch (FailedLoginException doNothing) {
    }

}

From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java

public void testBadPWLogin() throws Exception {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "BAD"));

    try {//from w  w  w. j  a v a2s. co m
        context.login();
        fail("Should have thrown a FailedLoginException");
    } catch (FailedLoginException doNothing) {
    }

}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationKerberosFilterTest.java

protected Subject loginTestUser() throws LoginException, IOException {
    LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() {

        @Override//w w w.j a  v a 2s. co  m
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(TESTPASS.toCharArray());
                }
                if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(TESTUSER);
                }
            }
        }
    });
    // attempt authentication
    lc.login();
    return lc.getSubject();
}

From source file:org.apache.atlas.web.filters.MetadataAuthenticationKerberosFilterIT.java

protected Subject loginTestUser() throws LoginException, IOException {
    LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() {

        @Override//from w ww . jav  a  2 s  .co  m
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                if (callbacks[i] instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callbacks[i];
                    passwordCallback.setPassword(TESTPASS.toCharArray());
                }
                if (callbacks[i] instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callbacks[i];
                    nameCallback.setName(TESTUSER);
                }
            }
        }
    });
    // attempt authentication
    lc.login();
    return lc.getSubject();
}

From source file:org.apache.catalina.realm.JAASRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return <code>null</code>.
 *
 * If there are any errors with the JDBC connection, executing
 * the query or anything we return null (don't authenticate). This
 * event is also logged, and the connection will be closed so that
 * a subsequent request will automatically re-open it.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 *  authenticating this username//  w w  w  . java2  s. co m
 */
public Principal authenticate(String username, String credentials) {

    // Establish a LoginContext to use for authentication
    try {
        LoginContext loginContext = null;
        if (appName == null)
            appName = "Tomcat";

        if (log.isDebugEnabled())
            log.debug("Authenticating " + appName + " " + username);

        // What if the LoginModule is in the container class loader ?
        //
        ClassLoader ocl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        try {
            loginContext = new LoginContext(appName, new JAASCallbackHandler(this, username, credentials));
        } catch (Throwable e) {
            log.error(sm.getString("jaasRealm.unexpectedError"), e);
            return (null);
        } finally {
            Thread.currentThread().setContextClassLoader(ocl);
        }

        if (log.isDebugEnabled())
            log.debug("Login context created " + username);

        // Negotiate a login via this LoginContext
        Subject subject = null;
        try {
            loginContext.login();
            subject = loginContext.getSubject();
            if (subject == null) {
                if (log.isDebugEnabled())
                    log.debug(sm.getString("jaasRealm.failedLogin", username));
                return (null);
            }
        } catch (AccountExpiredException e) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("jaasRealm.accountExpired", username));
            return (null);
        } catch (CredentialExpiredException e) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("jaasRealm.credentialExpired", username));
            return (null);
        } catch (FailedLoginException e) {
            if (log.isDebugEnabled())
                log.debug(sm.getString("jaasRealm.failedLogin", username));
            return (null);
        } catch (LoginException e) {
            log.warn(sm.getString("jaasRealm.loginException", username), e);
            return (null);
        } catch (Throwable e) {
            log.error(sm.getString("jaasRealm.unexpectedError"), e);
            return (null);
        }

        if (log.isDebugEnabled())
            log.debug("Getting principal " + subject);

        // Return the appropriate Principal for this authenticated Subject
        Principal principal = createPrincipal(username, subject);
        if (principal == null) {
            log.debug(sm.getString("jaasRealm.authenticateFailure", username));
            return (null);
        }
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
        }

        return (principal);
    } catch (Throwable t) {
        log.error("error ", t);
        return null;
    }
}

From source file:org.apache.coheigea.cxf.kerberos.authentication.TokenPreAuthTest.java

@org.junit.Test
public void unitTokenAuthGSSTest() throws Exception {

    // 1. Get a TGT from the KDC for the client + create an armor cache
    KrbClient client = new KrbClient();

    client.setKdcHost("localhost");
    client.setKdcTcpPort(kerbyServer.getKdcPort());
    client.setAllowUdp(false);//w  ww .jav a2 s.c o  m

    client.setKdcRealm(kerbyServer.getKdcSetting().getKdcRealm());
    client.init();

    TgtTicket tgt = client.requestTgt("alice@service.ws.apache.org", "alice");
    assertNotNull(tgt);

    // Write to cache
    Credential credential = new Credential(tgt);
    CredentialCache cCache = new CredentialCache();
    cCache.addCredential(credential);
    cCache.setPrimaryPrincipal(tgt.getClientPrincipal());

    File cCacheFile = File.createTempFile("krb5_alice@service.ws.apache.org", "cc");
    cCache.store(cCacheFile);

    // Now read in JAAS config + substitute in the armor cache file path value
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }
    File f = new File(basedir + "/target/test-classes/kerberos/kerberos.jaas");

    FileInputStream inputStream = new FileInputStream(f);
    String content = IOUtils.toString(inputStream, "UTF-8");
    inputStream.close();
    content = content.replaceAll("armorCacheVal", cCacheFile.getPath());

    File f2 = new File(basedir + "/target/test-classes/kerberos/kerberos.jaas");
    FileOutputStream outputStream = new FileOutputStream(f2);
    IOUtils.write(content, outputStream, "UTF-8");
    outputStream.close();

    // 2. Create a JWT token using CXF
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(new Date().getTime() / 1000L);
    claims.setExpiryTime(new Date().getTime() + (60L + 1000L));
    String address = "krbtgt/service.ws.apache.org@service.ws.apache.org";
    claims.setAudiences(Collections.singletonList(address));

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(Loader.getResourceAsStream("clientstore.jks"), "cspass".toCharArray());

    Properties signingProperties = new Properties();
    signingProperties.put(JoseConstants.RSSEC_SIGNATURE_ALGORITHM, SignatureAlgorithm.RS256.name());
    signingProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
    signingProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "myclientkey");
    signingProperties.put(JoseConstants.RSSEC_KEY_PSWD, "ckpass");

    JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);

    JwsSignatureProvider sigProvider = JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);

    String signedToken = jws.signWith(sigProvider);

    // Store the JWT token in the token cache
    File tokenCache = new File(basedir + "/target/tokencache.txt");
    if (!tokenCache.exists()) {
        tokenCache.createNewFile();
    }
    TokenCache.writeToken(signedToken, tokenCache.getPath());

    // 3. Now log in using JAAS
    LoginContext loginContext = new LoginContext("aliceTokenAuth", new KerberosCallbackHandler());
    loginContext.login();

    Subject clientSubject = loginContext.getSubject();
    //Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    //assertFalse(clientPrincipals.isEmpty());

    // Get the TGT
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());

    // Get the service ticket using GSS
    KerberosClientExceptionAction action = new KerberosClientExceptionAction(
            new KerberosPrincipal("alice@service.ws.apache.org"), "bob@service.ws.apache.org");
    byte[] ticket = (byte[]) Subject.doAs(clientSubject, action);
    assertNotNull(ticket);

    loginContext.logout();

    validateServiceTicket(ticket);

    cCacheFile.delete();
    tokenCache.delete();
}