Example usage for javax.security.auth Subject Subject

List of usage examples for javax.security.auth Subject Subject

Introduction

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

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

From source file:uk.org.openeyes.oink.security.HttpBasicPreauthProcessor.java

public void extractAuthenticationDetailsFromHttp(Exchange exchange) throws SecurityException {
    // get the username and password from the HTTP header
    // http://en.wikipedia.org/wiki/Basic_access_authentication
    String authorizationHeader = exchange.getIn().getHeader("Authorization", String.class);
    if (authorizationHeader == null) {
        throw new SecurityException("No HttpBasic Authorization Header was found in the request");
    }/*from  www.j  a v  a  2 s . com*/
    String basicPrefix = "Basic ";
    String userPassword = authorizationHeader.substring(basicPrefix.length());
    byte[] header = Base64.decodeBase64(userPassword.getBytes());
    if (header == null) {
        throw new SecurityException("Invalid Http Basic Authorization Header found in the request");
    }
    String userpass = new String(header);
    String[] tokens = userpass.split(":");

    // create an Authentication object
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(tokens[0],
            tokens[1]);

    // wrap it in a Subject
    Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    // place the Subject in the In message
    exchange.getIn().setHeader(Exchange.AUTHENTICATION, subject);

    logger.debug("Found HttpBasic Authentication header");

    // Spring security will intercept this and authenticate

}

From source file:org.infoscoop.account.simple.SimpleAccountManager.java

public Subject getSubject(String userid) throws Exception {
    Account account = (Account) this.getUser(userid);
    if (account == null)
        return null;

    Subject loginUser = new Subject();
    ISPrincipal p = new ISPrincipal(ISPrincipal.UID_PRINCIPAL, account.getUid());
    p.setDisplayName(account.getName());
    loginUser.getPrincipals().add(p);//from w  ww.ja  v a  2s.  c  o  m
    return loginUser;
}

From source file:org.josso.auth.scheme.NtlmAuthSchemeTest.java

public void testNtlmAuth() throws Exception {
    log.debug("geting bean NtlmAuthScheme...");
    NtlmAuthScheme scheme = (NtlmAuthScheme) applicationContext.getBean("josso-ntlm-authentication");
    assert scheme != null : "No authentication scheme configured";

    Credential domainCredential = scheme.newCredential(NtlmCredentialProvider.DOMAIN_CONTROLLER_CREDENTIAL,
            UniAddress.getByName("130.5.5.233"));
    Credential passCredential = scheme.newCredential(NtlmCredentialProvider.PASSWORD_AUTHENTICATION_CREDENTIAL,
            new NtlmPasswordAuthentication("NT-DOMAIN", "Administrator", "novascope"));
    Subject s = new Subject();
    scheme.initialize(new Credential[] { domainCredential, passCredential }, s);

    scheme.authenticate();/*from   w  w w.  j  a  v a2  s  .c o m*/
    scheme.confirm();

    assert s.getPrincipals().size() == 1 : "Expected one principal, got : " + s.getPrincipals().size();

    Principal user = s.getPrincipals().iterator().next();
    assert user.getName().equals("Administrator") : "Expected Administrator principal, got : " + user.getName();
}

From source file:fi.okm.mpass.idp.authn.impl.ExtractSocialPrincipalsFromSubjectTest.java

@Test
public void testIdentity() throws Exception {
    Subject subject = new Subject();

    SocialUserPrincipal socialUserPrincipalProviderId = new SocialUserPrincipal(Types.providerId, "providerId");
    subject.getPrincipals().add(socialUserPrincipalProviderId);
    SocialUserPrincipal socialUserPrincipalDisplayName = new SocialUserPrincipal(Types.displayName,
            "displayName");
    subject.getPrincipals().add(socialUserPrincipalDisplayName);
    SocialUserPrincipal socialUserPrincipalEmail = new SocialUserPrincipal(Types.email, "email");
    subject.getPrincipals().add(socialUserPrincipalEmail);
    SocialUserPrincipal socialUserPrincipalFirstName = new SocialUserPrincipal(Types.firstName, "firstName");
    subject.getPrincipals().add(socialUserPrincipalFirstName);
    SocialUserPrincipal socialUserPrincipalLastName = new SocialUserPrincipal(Types.lastName, "lastName");
    subject.getPrincipals().add(socialUserPrincipalLastName);
    SocialUserPrincipal socialUserPrincipalUserId = new SocialUserPrincipal(Types.userId, "userId");
    subject.getPrincipals().add(socialUserPrincipalUserId);
    SocialUserPrincipal socialUserPrincipalUS = new SocialUserPrincipal("unsupported", "unsupported");
    subject.getPrincipals().add(socialUserPrincipalUS);

    SocialUserContext suCtx = initContexts(subject);

    Assert.assertNotNull(suCtx);//from w  ww  . j a v a 2 s .  c om
    Assert.assertEquals(suCtx.getProviderId(), "providerId");
    Assert.assertEquals(suCtx.getDisplayName(), "displayName");
    Assert.assertEquals(suCtx.getEmail(), "email");
    Assert.assertEquals(suCtx.getFirstName(), "firstName");
    Assert.assertEquals(suCtx.getLastName(), "lastName");
    Assert.assertEquals(suCtx.getUserId(), "userId");
}

From source file:eu.openanalytics.rsb.security.JmxSecurityAuthenticator.java

@Override
public Subject authenticate(final Object credentials) {
    try {/*from  ww  w. j  a v  a2 s .c om*/
        final String[] info = (String[]) credentials;

        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(info[0], info[1]));

        final User authenticatedUser = (User) authentication.getPrincipal();

        if ((isRsbAdminPrincipal(authenticatedUser)) || (isRsbAdminRole(authenticatedUser))) {
            final Subject s = new Subject();
            s.getPrincipals().add(new JMXPrincipal(authentication.getName()));
            return s;
        } else {
            throw new SecurityException("Authenticated user " + authenticatedUser + " is not an RSB admin");
        }
    } catch (final Exception e) {
        LOGGER.error("Error when trying to authenticate JMX credentials of type: " + credentials.getClass(), e);

        throw new SecurityException(e);
    }
}

From source file:org.apache.nifi.security.krb.AbstractKerberosUser.java

/**
 * Performs a login using the specified principal and keytab.
 *
 * @throws LoginException if the login fails
 *//*from w  ww.  ja  va  2 s . c  o m*/
@Override
public synchronized void login() throws LoginException {
    if (isLoggedIn()) {
        return;
    }

    try {
        // If it's the first time ever calling login then we need to initialize a new context
        if (loginContext == null) {
            LOGGER.debug("Initializing new login context...");
            this.subject = new Subject();
            this.loginContext = createLoginContext(subject);
        }

        loginContext.login();
        loggedIn.set(true);
        LOGGER.debug("Successful login for {}", new Object[] { principal });
    } catch (LoginException le) {
        throw new LoginException("Unable to login with " + principal + " due to: " + le.getMessage());
    }
}

From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java

public Subject doAuthenticate(final String username, final String password) {
    try {//from ww w.j a  v  a 2s  .c o  m
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof NameCallback) {
                        ((NameCallback) callbacks[i]).setName(username);
                    } else if (callbacks[i] instanceof PasswordCallback) {
                        ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        loginContext.login();
        if (role != null && role.length() > 0) {
            String clazz = "org.apache.karaf.jaas.boot.principal.RolePrincipal";
            String name = role;
            int idx = role.indexOf(':');
            if (idx > 0) {
                clazz = role.substring(0, idx);
                name = role.substring(idx + 1);
            }
            boolean found = false;
            for (Principal p : subject.getPrincipals()) {
                if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new FailedLoginException("User does not have the required role " + role);
            }
        }
        return subject;
    } catch (AccountException e) {
        LOGGER.warn("Account failure", e);
        return null;
    } catch (LoginException e) {
        LOGGER.debug("Login failed", e);
        return null;
    } catch (GeneralSecurityException e) {
        LOGGER.error("General Security Exception", e);
        return null;
    }
}

From source file:fi.okm.mpass.idp.authn.impl.AbstractIdentity.java

/**
 * Returns user Subject based on key and profile.
 * /*from  www . j a  v  a2 s.c om*/
 * @param key
 *            Connection Key of the user
 * @param profile
 *            Profile of the user
 * @return User Subject
 */
public Subject getSubject(ConnectionKey key, UserProfile profile) {
    log.trace("Entering");
    Subject subject = new Subject();
    String userId = key.getProviderUserId();
    subject.getPrincipals().add(new UsernamePrincipal(userId));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.userId, userId));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.providerId, key.getProviderId()));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.email, profile.getEmail()));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.firstName, profile.getFirstName()));
    subject.getPrincipals().add(new SocialUserPrincipal(Types.lastName, profile.getLastName()));
    log.trace("Leaving");
    return subject;

}

From source file:org.opengroupware.logic.auth.OGoLoginModule.java

/**
 * This is a convenience function which sets up a JAAS login context with the
 * default database configuration,/*from   w ww . ja  va2s .  com*/
 * and then performs a login with the given login/password.
 * 
 * @param _db   - a setup OGoDatabase object
 * @param _user - the login name
 * @param _pwd  - the login password
 * @return null if the login failed, otherwise the LoginContext
 */
public static LoginContext jaasLogin(final EODatabase _db, final String _user, final String _pwd) {
    if (_db == null) {
        log.warn("got no database for JAAS login of user: " + _user);
        return null;
    }

    final Subject subject = new Subject();
    LoginContext jlc = null;
    try {
        jlc = new LoginContext("OGo", /* application     */
                subject, /* subject */
                new NamePasswordCallbackHandler(_user, _pwd), /* CallbackHandler */
                new OGoDefaultLoginConfig(_db) /* configuration */);
    } catch (LoginException e) {
        log.error("could not setup JAAS LoginContext", e);
    }
    if (jlc == null)
        return null;

    /* login */

    try {
        jlc.login();
    } catch (LoginException e) {
        jlc = null;
        return null;
    }

    return jlc;
}

From source file:org.apache.nifi.security.krb.StandardKeytabUser.java

/**
 * Performs a login using the specified principal and keytab.
 *
 * @throws LoginException if the login fails
 *//*ww w. j  a v  a 2  s  . c o m*/
@Override
public synchronized void login() throws LoginException {
    if (isLoggedIn()) {
        return;
    }

    try {
        // If it's the first time ever calling login then we need to initialize a new context
        if (loginContext == null) {
            LOGGER.debug("Initializing new login context...");
            this.subject = new Subject();

            final Configuration config = new KeytabConfiguration(principal, keytabFile);
            this.loginContext = new LoginContext("KeytabConf", subject, null, config);
        }

        loginContext.login();
        loggedIn.set(true);
        LOGGER.debug("Successful login for {}", new Object[] { principal });
    } catch (LoginException le) {
        throw new LoginException(
                "Unable to login with " + principal + " and " + keytabFile + " due to: " + le.getMessage());
    }
}