Example usage for javax.security.auth Subject getSubject

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

Introduction

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

Prototype

public static Subject getSubject(final AccessControlContext acc) 

Source Link

Document

Get the Subject associated with the provided AccessControlContext .

Usage

From source file:net.sourceforge.safr.sample.usermgnt.service.UserServiceImpl.java

private static Principal currentUserPrincipal() {
    Subject s = Subject.getSubject(AccessController.getContext());
    return s.getPrincipals(UserPrincipal.class).iterator().next();
}

From source file:org.apache.hive.service.auth.HttpAuthUtils.java

/**
 * @return Stringified Base64 encoded kerberosAuthHeader on success
 * @throws Exception//from  ww w.ja v a  2s. c o  m
 */
public static String getKerberosServiceTicket(String principal, String host, String serverHttpUrl,
        boolean assumeSubject) throws Exception {
    String serverPrincipal = ShimLoader.getHadoopThriftAuthBridge().getServerPrincipal(principal, host);
    if (assumeSubject) {
        // With this option, we're assuming that the external application,
        // using the JDBC driver has done a JAAS kerberos login already
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null) {
            throw new Exception("The Subject is not set");
        }
        return Subject.doAs(subject, new HttpKerberosClientAction(serverPrincipal, serverHttpUrl));
    } else {
        // JAAS login from ticket cache to setup the client UserGroupInformation
        UserGroupInformation clientUGI = ShimLoader.getHadoopThriftAuthBridge()
                .getCurrentUGIWithConf("kerberos");
        return clientUGI.doAs(new HttpKerberosClientAction(serverPrincipal, serverHttpUrl));
    }
}

From source file:net.sourceforge.safr.jaas.permission.PermissionManagerImpl.java

public void checkPermission(Permission permission) {
    Subject current = Subject.getSubject(AccessController.getContext());
    if (!implies(permission, current) && activated) {
        throw new AccessControlException("access denied", permission);
    }/*from  w  w w.j av a 2 s .  c om*/
}

From source file:org.apache.hadoop.gateway.hive.HiveHttpClientDispatch.java

protected Principal getPrimaryPrincipal() {
    Principal principal = null;//from w w  w.  j a  v a 2s  .c  o m
    Subject subject = Subject.getSubject(AccessController.getContext());
    if (subject != null) {
        principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
    }
    return principal;
}

From source file:com.cloudera.alfredo.client.KerberosAuthenticator.java

/**
 * Implements the SPNEGO authentication sequence interaction using the current default principal
 * in the Kerberos cache (normally set via kinit).
 *
 * @param token the authencation token being used for the user.
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 *///  w w w .  j  av a  2  s. c  o  m
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null) {
            subject = new Subject();
            LoginContext login = new LoginContext("", subject);
            login.login();
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator.this.url.getHost();
                    GSSName serviceName = gssManager.createName(servicePrincipal,
                            GSSUtil.NT_GSS_KRB5_PRINCIPAL);
                    gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_OID, null,
                            GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:graphql.servlet.GraphQLServlet.java

private void query(String query, String operationName, Map<String, Object> variables, GraphQLSchema schema,
        HttpServletRequest req, HttpServletResponse resp, GraphQLContext context) throws IOException {
    if (Subject.getSubject(AccessController.getContext()) == null && context.getSubject().isPresent()) {
        Subject.doAs(context.getSubject().get(), new PrivilegedAction<Void>() {
            @Override//from w ww . j  a  v  a2 s.  c o m
            @SneakyThrows
            public Void run() {
                query(query, operationName, variables, schema, req, resp, context);
                return null;
            }
        });
    } else {
        Map<String, Object> vars = transformVariables(schema, query, variables);
        operationListeners.forEach(l -> l.beforeGraphQLOperation(context, operationName, query, vars));

        ExecutionResult result = new GraphQL(schema, getExecutionStrategy()).execute(query, operationName,
                context, vars);
        resp.setContentType("application/json;charset=utf-8");
        if (result.getErrors().isEmpty()) {
            Map<String, Object> dict = new HashMap<>();
            dict.put("data", result.getData());
            resp.getWriter().write(new ObjectMapper().writeValueAsString(dict));
            operationListeners.forEach(
                    l -> l.onSuccessfulGraphQLOperation(context, operationName, query, vars, result.getData()));
        } else {
            resp.setStatus(500);
            List<GraphQLError> errors = getGraphQLErrors(result);
            Map<String, Object> dict = new HashMap<>();
            dict.put("errors", errors);

            resp.getWriter().write(new ObjectMapper().writeValueAsString(dict));
            operationListeners.forEach(
                    l -> l.onFailedGraphQLOperation(context, operationName, query, vars, result.getErrors()));
        }
    }
}

From source file:com.lucidworks.security.authentication.client.KerberosAuthenticator.java

/**
 * Implements the SPNEGO authentication sequence interaction using the current default principal
 * in the Kerberos cache (normally set via kinit).
 *
 * @param token the authentication token being used for the user.
 *
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 *//*from   ww  w  .j a v  a  2 s.  c o  m*/
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null) {
            LOG.debug("No subject in context, logging in");
            subject = new Subject();
            LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration());
            login.login();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Using subject: " + subject);
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP",
                            KerberosAuthenticator.this.url.getHost());
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:com.srotya.collectd.storm.StormNimbusMetrics.java

@Override
public int config(OConfigItem config) {
    nimbusAddresses = new ArrayList<>();
    String jaasPath = "jaas.conf";
    List<OConfigItem> children = config.getChildren();
    for (OConfigItem child : children) {
        switch (child.getKey().toLowerCase()) {
        case "address":
            for (OConfigValue nimbus : child.getValues()) {
                try {
                    new URI(nimbus.toString());
                } catch (Exception e) {
                    Collectd.logError("Bad URI " + nimbus + " for Nimbus, error:" + e.getMessage());
                    return -1;
                }//from  w ww. j  a v a 2  s .  c  o m
                nimbusAddresses.add(nimbus.getString());
            }
            break;
        case "kerberos":
            kerberos = child.getValues().get(0).getBoolean();
            break;
        case "jaas":
            jaasPath = child.getValues().get(0).getString();
            break;
        }
    }
    Collectd.logInfo("Storm Nimbus Plugin: using following Nimbuses:" + nimbusAddresses);
    Collectd.logInfo("Storm Nimbus Plugin: using kerberos:" + kerberos);

    builder = HttpClientBuilder.create();
    context = HttpClientContext.create();
    if (kerberos) {
        System.setProperty("java.security.auth.login.config", jaasPath);
        System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "true");

        login();

        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // This may seem odd, but specifying 'null' as principal tells java
        // to
        // use the logged in user's credentials
        Credentials useJaasCreds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };
        credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds);
        context.setCredentialsProvider(credentialsProvider);

    } else {
        subject = Subject.getSubject(AccessController.getContext());
    }
    return 0;
}

From source file:com.ikon.module.jcr.stuff.JCRUtils.java

/**
 * Get JCR Session//from www.  j a  va  2 s.  co m
 */
public static Session getSession()
        throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException {
    Subject subject = null;
    Object obj = null;

    // Resolve subject
    // Subject userSubject=(Subject)PolicyContext.getContext("javax.security.auth.Subject.container");
    if (EnvironmentDetector.isServerJBoss()) {
        try {
            InitialContext ctx = new InitialContext();
            subject = (Subject) ctx.lookup("java:/comp/env/security/subject");
            ctx.close();
        } catch (NamingException e) {
            throw new javax.jcr.LoginException(e.getMessage());
        }
    } else if (EnvironmentDetector.isServerTomcat()) {
        subject = Subject.getSubject(AccessController.getContext());
    }

    // Obtain JCR session
    if (subject != null) {
        obj = Subject.doAs(subject, new PrivilegedAction<Object>() {
            public Object run() {
                Session s = null;

                try {
                    s = JcrRepositoryModule.getRepository().login();
                } catch (javax.jcr.LoginException e) {
                    return e;
                } catch (javax.jcr.RepositoryException e) {
                    return e;
                }

                return s;
            }
        });
    }

    // Validate JCR session
    if (obj instanceof javax.jcr.LoginException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.RepositoryException) {
        throw (javax.jcr.RepositoryException) obj;
    } else if (obj instanceof javax.jcr.Session) {
        Session session = (javax.jcr.Session) obj;
        log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions,
                session, StackTraceUtils.whoCalledMe() });
        JcrAuthModule.loadUserData(session);
        return session;
    } else {
        return null;
    }
}

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

/**
 * Return the current user, including any doAs in the current stack.
 *
 * @return the current user// w w w.  java2 s  .c  o m
 *
 * @throws IOException if login fails
 */

public synchronized static UserGroupInformation getCurrentUser() throws IOException {
    AccessControlContext context = AccessController.getContext();
    Subject subject = Subject.getSubject(context);
    if (subject == null || subject.getPrincipals(User.class).isEmpty()) {
        return getLoginUser();
    } else {
        return new UserGroupInformation(subject);
    }
}