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(boolean readOnly, Set<? extends Principal> principals, Set<?> pubCredentials,
        Set<?> privCredentials) 

Source Link

Document

Create an instance of a Subject with Principals and credentials.

Usage

From source file:org.apache.jackrabbit.core.SessionImpl.java

/**
 * Returns a read only copy of the <code>Subject</code> associated with this
 * session./*w w w  .  ja  va2 s.co  m*/
 *
 * @return a read only copy of <code>Subject</code> associated with this session
 */
public Subject getSubject() {
    Subject readOnly = new Subject(true, subject.getPrincipals(), subject.getPublicCredentials(),
            subject.getPrivateCredentials());
    return readOnly;
}

From source file:org.apache.jackrabbit.core.SessionImpl.java

/**
  * Creates a new session with the same subject as this sessions but to a
  * different workspace. The returned session is a newly logged in session,
  * with the same subject but a different workspace. Even if the given
  * workspace is the same as this sessions one, the implementation must
  * return a new session object.//from  www  .  ja  v  a 2s . c o m
  *
  * @param workspaceName name of the workspace to acquire a session for.
  * @return A session to the requested workspace for the same authenticated
  *         subject.
  * @throws AccessDeniedException in case the current Subject is not allowed
  *         to access the requested Workspace
  * @throws NoSuchWorkspaceException If the named workspace does not exist.
  * @throws RepositoryException in any other exceptional state
  */
public Session createSession(String workspaceName)
        throws AccessDeniedException, NoSuchWorkspaceException, RepositoryException {
    if (workspaceName == null) {
        workspaceName = repositoryContext.getWorkspaceManager().getDefaultWorkspaceName();
    }
    Subject newSubject = new Subject(subject.isReadOnly(), subject.getPrincipals(),
            subject.getPublicCredentials(), subject.getPrivateCredentials());
    return repositoryContext.getWorkspaceManager().createSession(newSubject, workspaceName);
}

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

public HttpResponse callRestUrl(final String url, final String userId, HTTP operation) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Calling YarnClient %s %s %s", this.principal, this.keytab, url));
    }/*from  www.  j  a v  a2s .  com*/
    javax.security.auth.login.Configuration config = new javax.security.auth.login.Configuration() {
        @SuppressWarnings("serial")
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] { new AppConfigurationEntry(
                    "com.sun.security.auth.module.Krb5LoginModule",
                    AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
                        {
                            put("useTicketCache", "false");
                            put("useKeyTab", "true");
                            put("keyTab", keytab);
                            // Krb5 in GSS API needs to be refreshed so it does not throw the error
                            // Specified version of key is not available
                            put("refreshKrb5Config", "true");
                            put("principal", principal);
                            put("storeKey", "true");
                            put("doNotPrompt", "true");
                            put("isInitiator", "true");
                            if (LOGGER.isDebugEnabled()) {
                                put("debug", "true");
                            }
                        }
                    }) };
        }
    };

    Set<Principal> principals = new HashSet<Principal>(1);
    principals.add(new KerberosPrincipal(userId));
    Subject sub = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
    try {
        // Authentication module: Krb5Login
        LoginContext loginContext = new LoginContext("Krb5Login", sub, null, config);
        loginContext.login();
        Subject serviceSubject = loginContext.getSubject();
        return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
            HttpResponse httpResponse = null;

            @Override
            public HttpResponse run() {
                try {
                    HttpUriRequest request = null;
                    switch (operation) {
                    case DELETE:
                        request = new HttpDelete(url);
                        break;
                    case POST:
                        request = new HttpPost(url);
                        break;
                    default:
                        request = new HttpGet(url);
                        break;
                    }

                    HttpClient spengoClient = buildSpengoHttpClient();
                    httpResponse = spengoClient.execute(request);
                    return httpResponse;
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
                return httpResponse;
            }
        });
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

private Subject fetchSubjectFromLoginModuleWithPrincipal(String jaasContextName, String servicePrincipal,
        Krb5LoginConfig loginConfig) throws LoginException {
    final Set<Principal> princ = new HashSet<Principal>(1);
    princ.add(new KerberosPrincipal(servicePrincipal));
    // Create a new editable Subject
    final Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
    return fetchSubjectFromLoginModule(jaasContextName, sub, loginConfig);
}

From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java

public static <T> T doAsKerberosUser(String principal, String keytab, final Callable<T> callable)
        throws Exception {
    LoginContext loginContext = null;
    try {//w w w .  ja  v a 2 s .c  o m
        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(principal));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
        loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal, keytab));
        loginContext.login();
        subject = loginContext.getSubject();
        return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
            @Override
            public T run() throws Exception {
                return callable.call();
            }
        });
    } catch (PrivilegedActionException ex) {
        throw ex.getException();
    } finally {
        if (loginContext != null) {
            loginContext.logout();
        }
    }
}

From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java

private void initializeKerberosLogin() throws ServletException {
    String keytab;/* w w w.  jav a 2s . c om*/

    try {
        if (serverPrincipal == null || serverPrincipal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = serverKeytab;
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(serverPrincipal));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

        DruidKerberosConfiguration kerberosConfiguration = new DruidKerberosConfiguration(keytab,
                serverPrincipal);

        log.info("Login using keytab " + keytab + ", for principal " + serverPrincipal);
        loginContext = new LoginContext("", subject, null, kerberosConfiguration);
        loginContext.login();

        log.info("Initialized, principal %s from keytab %s", serverPrincipal, keytab);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

private void initializeKerberosLogin() throws ServletException {
    String principal;/*from  w  w w  . jav a 2  s  . c  o  m*/
    String keytab;

    try {
        principal = SecurityUtil.getServerPrincipal(serverPrincipal, node.getHost());
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = serverKeytab;
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(principal));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

        DruidKerberosConfiguration kerberosConfiguration = new DruidKerberosConfiguration(keytab, principal);

        log.info("Login using keytab " + keytab + ", for principal " + principal);
        loginContext = new LoginContext("", subject, null, kerberosConfiguration);
        loginContext.login();

        log.info("Initialized, principal %s from keytab %s", principal, keytab);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * Create a Kerberos Subject for the Principal whose name is passed
 * /*ww  w.  java2s. com*/
 * @param name
 *            the name to use
 * @return a valid Subject
 */
private Subject createSubject(GSSName name) {
    // return com.sun.security.jgss.GSSUtil.createSubject(name, null); //
    // this was Sun JVM only ;-)

    final Set<KerberosPrincipal> krb5Principals = new HashSet<KerberosPrincipal>();

    try {
        // First create a canonical string representation of KRB5
        final String krb5name = name.canonicalize(GSS_KRB5_MECH_OID).toString();

        // Then, create a Kerberos Principal from the canonical name
        final KerberosPrincipal krbPrinc = new KerberosPrincipal(krb5name);

        krb5Principals.add(krbPrinc);
    } catch (final GSSException e) {
        LOG.log(Level.SEVERE, "Unable to create the Kerberos context", e);
    }

    return new Subject(false, krb5Principals, new HashSet<Object>(), new HashSet<Object>());

}

From source file:org.apache.hadoop.hive.shims.Hadoop23Shims.java

@Override
public UserGroupInformation cloneUgi(UserGroupInformation baseUgi) throws IOException {
    // Based on UserGroupInformation::createProxyUser.
    // TODO: use a proper method after we can depend on HADOOP-13081.
    if (getSubjectMethod == null) {
        throw new IOException("The UGI method was not found: " + ugiCloneError);
    }//from w  w w.  ja  va2  s.  c o  m
    try {
        Subject origSubject = (Subject) getSubjectMethod.invoke(baseUgi);

        Subject subject = new Subject(false, origSubject.getPrincipals(),
                cloneCredentials(origSubject.getPublicCredentials()),
                cloneCredentials(origSubject.getPrivateCredentials()));
        return ugiCtor.newInstance(subject);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new IOException(e);
    }
}