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:org.apache.wiki.auth.AuthenticationManager.java

/**
 * Instantiates and executes a single JAAS
 * {@link javax.security.auth.spi.LoginModule}, and returns a Set of
 * Principals that results from a successful login. The LoginModule is instantiated,
 * then its {@link javax.security.auth.spi.LoginModule#initialize(Subject, CallbackHandler, Map, Map)}
 * method is called. The parameters passed to <code>initialize</code> is a 
 * dummy Subject, an empty shared-state Map, and an options Map the caller supplies.
 * //  w  w  w.j  a v  a 2 s  . c o m
 * @param clazz
 *            the LoginModule class to instantiate
 * @param handler
 *            the callback handler to supply to the LoginModule
 * @param options
 *            a Map of key/value strings for initializing the LoginModule
 * @return the set of Principals returned by the JAAS method {@link Subject#getPrincipals()}
 * @throws WikiSecurityException
 *             if the LoginModule could not be instantiated for any reason
 */
protected Set<Principal> doJAASLogin(Class<? extends LoginModule> clazz, CallbackHandler handler,
        Map<String, String> options) throws WikiSecurityException {
    // Instantiate the login module
    LoginModule loginModule = null;
    try {
        loginModule = clazz.newInstance();
    } catch (InstantiationException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    }

    // Initialize the LoginModule
    Subject subject = new Subject();
    loginModule.initialize(subject, handler, EMPTY_MAP, options);

    // Try to log in:
    boolean loginSucceeded = false;
    boolean commitSucceeded = false;
    try {
        loginSucceeded = loginModule.login();
        if (loginSucceeded) {
            commitSucceeded = loginModule.commit();
        }
    } catch (LoginException e) {
        // Login or commit failed! No principal for you!
    }

    // If we successfully logged in & committed, return all the principals
    if (loginSucceeded && commitSucceeded) {
        return subject.getPrincipals();
    }
    return NO_PRINCIPALS;
}

From source file:org.apache.ranger.biz.KmsKeyMgr.java

private Subject getSubjectForKerberos(String provider) throws Exception {
    String userName = getKMSUserName(provider);
    String password = getKMSPassword(provider);
    String nameRules = PropertiesUtil.getProperty(NAME_RULES);
    if (StringUtils.isEmpty(nameRules)) {
        KerberosName.setRules("DEFAULT");
    } else {/*www .  j  a  va  2  s  .  c om*/
        KerberosName.setRules(nameRules);
    }
    Subject sub = new Subject();
    String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL),
            PropertiesUtil.getProperty(HOST_NAME));
    if (checkKerberos()) {
        if (SecureClientLogin.isKerberosCredentialExists(rangerPrincipal,
                PropertiesUtil.getProperty(ADMIN_USER_KEYTAB))) {
            sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal,
                    PropertiesUtil.getProperty(ADMIN_USER_KEYTAB), nameRules);
        } else {
            sub = SecureClientLogin.loginUserWithPassword(userName, password);
        }
    } else {
        sub = SecureClientLogin.login(userName);
    }
    return sub;
}

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Log a user in from a keytab file. Loads a user identity from a keytab
 * file and login them in. This new user does not affect the currently
 * logged-in user./* w ww  . j a  va 2s  .  c  o  m*/
 * @param user the principal name to load from the keytab
 * @param path the path to the keytab file
 * @throws IOException if the keytab file can't be read
 */
public synchronized static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path)
        throws IOException {
    if (!isSecurityEnabled())
        return UserGroupInformation.getCurrentUser();
    String oldKeytabFile = null;
    String oldKeytabPrincipal = null;

    long start = 0;
    try {
        oldKeytabFile = keytabFile;
        oldKeytabPrincipal = keytabPrincipal;
        keytabFile = path;
        keytabPrincipal = user;
        Subject subject = new Subject();

        LoginContext login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject);

        start = System.currentTimeMillis();
        login.login();
        metrics.addLoginSuccess(System.currentTimeMillis() - start);
        UserGroupInformation newLoginUser = new UserGroupInformation(subject);
        newLoginUser.setLogin(login);
        newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);

        return newLoginUser;
    } catch (LoginException le) {
        if (start > 0) {
            metrics.addLoginFailure(System.currentTimeMillis() - start);
        }
        throw new IOException("Login failure for " + user + " from keytab " + path, le);
    } finally {
        if (oldKeytabFile != null)
            keytabFile = oldKeytabFile;
        if (oldKeytabPrincipal != null)
            keytabPrincipal = oldKeytabPrincipal;
    }
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Log in a user using the given subject
 *
 * @throws IOException if login fails//ww  w .  j  a  v a 2s  .  c  o  m
 * @parma subject the subject to use when logging in a user, or null to create a new subject.
 */

public synchronized static void loginUserFromSubject(Subject subject) throws IOException {
    ensureInitialized();
    try {
        if (subject == null) {
            subject = new Subject();
        }
        LoginContext login = newLoginContext(authenticationMethod.getLoginAppName(), subject,
                new HadoopConfiguration());
        login.login();
        UserGroupInformation realUser = new UserGroupInformation(subject);
        realUser.setLogin(login);
        realUser.setAuthenticationMethod(authenticationMethod);
        realUser = new UserGroupInformation(login.getSubject());
        // If the HADOOP_PROXY_USER environment variable or property
        // is specified, create a proxy user as the logged in user.
        String proxyUser = System.getenv(HADOOP_PROXY_USER);
        if (proxyUser == null) {
            proxyUser = System.getProperty(HADOOP_PROXY_USER);
        }
        loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser);

        String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
        if (fileLocation != null) {
            // Load the token storage file and put all of the tokens into the
            // user. Don't use the FileSystem API for reading since it has a lock
            // cycle (HADOOP-9212).
            //                Credentials cred = Credentials.readTokenStorageFile(
            //                        new File(fileLocation), conf);
            //                loginUser.addCredentials(cred);
        }
        loginUser.spawnAutoRenewalThreadForUserCreds();
    } catch (LoginException le) {
        LOG.debug("failure to login", le);
        throw new IOException("failure to login", le);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("UGI loginUser:" + loginUser);
    }
}

From source file:org.apache.storm.utils.ServerUtils.java

public static Subject principalNameToSubject(String name) {
    SingleUserPrincipal principal = new SingleUserPrincipal(name);
    Subject sub = new Subject();
    sub.getPrincipals().add(principal);//  ww  w  .  ja v  a 2s  .co  m
    return sub;
}

From source file:com.ecyrd.jspwiki.auth.SecurityVerifier.java

/**
 * Verifies that a particular Principal possesses a Permission, as defined
 * in the security policy file.//from  w  w w . j a  va2  s. c  o m
 * @param principal the principal
 * @param permission the permission
 * @return the result, based on consultation with the active Java security
 *         policy
 */
protected final boolean verifyStaticPermission(Principal principal, final Permission permission) {
    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    boolean allowedByGlobalPolicy = ((Boolean) Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() {
        public Object run() {
            try {
                AccessController.checkPermission(permission);
                return Boolean.TRUE;
            } catch (AccessControlException e) {
                return Boolean.FALSE;
            }
        }
    }, null)).booleanValue();

    if (allowedByGlobalPolicy) {
        return true;
    }

    // Check local policy
    Principal[] principals = new Principal[] { principal };
    return m_engine.getAuthorizationManager().allowedByLocalPolicy(principals, permission);
}

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Create a user from a login name. It is intended to be used for remote
 * users in RPC, since it won't have any credentials.
 * @param user the full user principal name, must not be empty or null
 * @return the UserGroupInformation for the remote user.
 *//*ww w  . java 2 s.  c  om*/
public static UserGroupInformation createRemoteUser(String user) {
    if (user == null || "".equals(user)) {
        throw new IllegalArgumentException("Null user");
    }
    Subject subject = new Subject();
    subject.getPrincipals().add(new User(user));
    UserGroupInformation result = new UserGroupInformation(subject);
    result.setAuthenticationMethod(AuthenticationMethod.SIMPLE);
    return result;
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

private void getOwners(Node node, boolean resolve) {
    if (node == null || node.appData == null)
        return;/*  ww  w.j a  va2s .c  om*/

    NodeID nid = (NodeID) node.appData;
    if (nid.owner != null)
        return; // already loaded (parent loop below)

    String ownerPropertyString = null;
    Subject s;
    if (resolve) {
        s = identityCache.get(nid.ownerObject);

        if (s == null) {
            log.debug("lookup subject for owner=" + nid.ownerObject);
            s = identManager.toSubject(nid.ownerObject);
            prof.checkpoint("IdentityManager.toSubject");
            identityCache.put(nid.ownerObject, s);
        } else {
            log.debug("found cached subject for owner=" + nid.ownerObject);
        }

        ownerPropertyString = identManager.toOwnerString(s);
    } else {
        log.debug("creating numeric principal only subject.");
        s = new Subject();
        if (nid.ownerObject != null) {
            Integer ownerInt = (Integer) nid.ownerObject;
            UUID numericID = new UUID(0L, (long) ownerInt);
            s.getPrincipals().add(new NumericPrincipal(numericID));
            ownerPropertyString = ownerInt.toString();
        }
    }

    nid.owner = s;
    if (ownerPropertyString != null)
        node.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CREATOR, ownerPropertyString));

    Node parent = node.getParent();
    while (parent != null) {
        getOwners(parent, resolve);
        parent = parent.getParent();
    }
}

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Create a proxy user using username of the effective user and the ugi of the
 * real user./*from  w  w w.  ja  v a 2 s . c  o  m*/
 * @param user
 * @param realUser
 * @return proxyUser ugi
 */
public static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser) {
    if (user == null || "".equals(user)) {
        throw new IllegalArgumentException("Null user");
    }
    if (realUser == null) {
        throw new IllegalArgumentException("Null real user");
    }
    Subject subject = new Subject();
    Set<Principal> principals = subject.getPrincipals();
    principals.add(new User(user));
    principals.add(new RealUser(realUser));
    UserGroupInformation result = new UserGroupInformation(subject);
    result.setAuthenticationMethod(AuthenticationMethod.PROXY);
    return result;
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Log 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.//from  ww w  .  j  ava2  s. com
 *
 * @param user the principal name to load from the keytab
 * @param path the path to the keytab file
 *
 * @throws IOException if the keytab file can't be read
 */

public synchronized static void loginUserFromKeytab(String user, String path) throws IOException {
    if (!isSecurityEnabled())
        return;

    keytabFile = path;
    keytabPrincipal = user;
    Subject subject = new Subject();
    LoginContext login;
    long start = 0;
    try {
        login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject,
                new HadoopConfiguration());
        start = Time.now();
        login.login();
        //            metrics.loginSuccess.add(Time.now() - start);
        loginUser = new UserGroupInformation(subject);
        loginUser.setLogin(login);
        loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    } catch (LoginException le) {
        if (start > 0) {
            //                metrics.loginFailure.add(Time.now() - start);
        }
        throw new IOException("Login failure for " + user + " from keytab " + path + ": " + le, le);
    }
    LOG.info("Login successful for user " + keytabPrincipal + " using keytab file " + keytabFile);
}