Example usage for javax.security.auth Subject doAs

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

Introduction

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

Prototype

public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action)
        throws java.security.PrivilegedActionException 

Source Link

Document

Perform work as a particular Subject .

Usage

From source file:org.apache.ranger.tagsync.sink.tagadmin.TagAdminRESTSink.java

private ServiceTags doUpload(ServiceTags serviceTags) throws Exception {
    if (!StringUtils.isEmpty(authenticationType)
            && authenticationType.trim().equalsIgnoreCase(AUTH_TYPE_KERBEROS)
            && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) {
        try {//from   w w  w  .j  a  va2  s  . c o m
            Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Using Principal = " + principal + ", keytab = " + keytab);
            }
            final ServiceTags serviceTag = serviceTags;
            ServiceTags ret = Subject.doAs(sub, new PrivilegedAction<ServiceTags>() {
                @Override
                public ServiceTags run() {
                    try {
                        return uploadServiceTags(serviceTag);
                    } catch (Exception e) {
                        LOG.error("Upload of service-tags failed with message ", e);
                    }
                    return null;
                }
            });
            return ret;
        } catch (Exception e) {
            LOG.error("Upload of service-tags failed with message ", e);
        }
        return null;
    } else {
        return uploadServiceTags(serviceTags);
    }
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.KerberosTokenGenerator.java

private void initiateSecurityContext() throws GSSException {
    GSSManager manager = GSSManager.getInstance();
    GSSName gssSPN = manager.createName(spn, null);

    final GSSContext context = manager.createContext(gssSPN, new Oid(SPNEGO_OID), null,
            GSSContext.DEFAULT_LIFETIME);

    // The GSS context initiation has to be performed as a privilegedv action.
    this.serviceTicket = Subject.doAs(subject, new PrivilegedAction<byte[]>() {
        public byte[] run() {
            try {
                byte[] token = new byte[0];
                context.requestMutualAuth(true);
                context.requestCredDeleg(true);
                return context.initSecContext(token, 0, token.length);
            } catch (GSSException e) {
                String msg = e.getMessage();
                if (StringUtils.isBlank(msg)) {
                    msg = "Authentication failed.";
                }//from  w w w  .j a  v  a2s. co m
                log.error(msg, e);
                throw new AuthenticationException(msg, e);
            }
        }
    });
}

From source file:org.apache.lens.server.auth.SpnegoAuthenticationFilter.java

@Override
public void filter(ContainerRequestContext context) {
    Principal userPrincipal = context.getSecurityContext().getUserPrincipal();
    if (userPrincipal != null) {
        log.info("Authentication already done for principal {}, skipping this filter...",
                userPrincipal.getName());
        return;/*from   w w  w  .j a  v a 2  s . com*/
    }
    // only authenticate when @Authenticate is present on resource
    if (resourceInfo.getResourceClass() == null || resourceInfo.getResourceMethod() == null) {
        return;
    }
    if (!(resourceInfo.getResourceClass().isAnnotationPresent(Authenticate.class)
            || resourceInfo.getResourceMethod().isAnnotationPresent(Authenticate.class))) {
        return;
    }
    List<String> authHeaders = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (authHeaders == null || authHeaders.size() != 1) {
        log.info("No Authorization header is available");
        throw toNotAuthorizedException(null, getFaultResponse());
    }
    String[] authPair = StringUtils.split(authHeaders.get(0), " ");
    if (authPair.length != 2 || !AuthScheme.NEGOTIATE.getName().equalsIgnoreCase(authPair[0])) {
        log.info("Negotiate Authorization scheme is expected");
        throw toNotAuthorizedException(null, getFaultResponse());
    }

    byte[] serviceTicket = getServiceTicket(authPair[1]);

    try {
        Subject serviceSubject = loginAndGetSubject();

        GSSContext gssContext = createGSSContext();

        Subject.doAs(serviceSubject, new ValidateServiceTicketAction(gssContext, serviceTicket));

        final GSSName srcName = gssContext.getSrcName();
        if (srcName == null) {
            throw toNotAuthorizedException(null, getFaultResponse());
        }

        String complexUserName = srcName.toString();

        String simpleUserName = complexUserName;
        int index = simpleUserName.lastIndexOf('@');
        if (index > 0) {
            simpleUserName = simpleUserName.substring(0, index);
        }
        context.setSecurityContext(createSecurityContext(simpleUserName, AUTH_SCHEME.getName()));
        if (!gssContext.getCredDelegState()) {
            gssContext.dispose();
            gssContext = null;
        }

    } catch (LoginException e) {
        log.info("Unsuccessful JAAS login for the service principal: " + e.getMessage());
        throw toNotAuthorizedException(e, getFaultResponse());
    } catch (GSSException e) {
        log.info("GSS API exception: " + e.getMessage());
        throw toNotAuthorizedException(e, getFaultResponse());
    } catch (PrivilegedActionException e) {
        log.info("PrivilegedActionException: " + e.getMessage());
        throw toNotAuthorizedException(e, getFaultResponse());
    }
}

From source file:org.apache.ranger.services.sqoop.client.SqoopClient.java

public List<String> getLinkList(final String linkMatching, final List<String> existingLinks) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(/*from  w w w . j a va  2s .c  om*/
                "Get sqoop link list for linkMatching: " + linkMatching + ", existingLinks: " + existingLinks);
    }
    Subject subj = getLoginSubject();
    if (subj == null) {
        return Collections.emptyList();
    }

    List<String> ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {

        @Override
        public List<String> run() {

            ClientResponse response = getClientResponse(sqoopUrl, SQOOP_LINK_API_ENDPOINT, userName);

            SqoopLinksResponse sqoopLinksResponse = getSqoopResourceResponse(response,
                    SqoopLinksResponse.class);
            if (sqoopLinksResponse == null || CollectionUtils.isEmpty(sqoopLinksResponse.getLinks())) {
                return Collections.emptyList();
            }
            List<String> linkResponses = new ArrayList<>();
            for (SqoopLinkResponse sqoopLinkResponse : sqoopLinksResponse.getLinks()) {
                linkResponses.add(sqoopLinkResponse.getName());
            }

            List<String> links = null;
            if (CollectionUtils.isNotEmpty(linkResponses)) {
                links = filterResourceFromResponse(linkMatching, existingLinks, linkResponses);
            }
            return links;
        }
    });

    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop link list result: " + ret);
    }
    return ret;
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.krb5.Krb5Authenticator.java

@Override
public void initPlugin(Map<String, String> parameters) {

    try {/*w  w  w . ja  v  a2  s .c  om*/
        this.loginContext = new LoginContext("Nuxeo");
        // note: we assume that all configuration is done in loginconfig, so there are NO parameters here
        loginContext.login();
        serverCredential = Subject.doAs(loginContext.getSubject(), getServerCredential);
        logger.debug("Successfully initialized Kerberos auth module");
    } catch (LoginException le) {
        logger.error("Cannot create LoginContext, disabling Kerberos module", le);
        this.disabled = true;
    } catch (PrivilegedActionException pae) {
        logger.error("Cannot get server credentials, disabling Kerberos module", pae);
        this.disabled = true;
    }

}

From source file:backtype.storm.security.auth.kerberos.KerberosSaslTransportPlugin.java

@Override
public TTransport connect(TTransport transport, String serverHost, String asUser)
        throws TTransportException, IOException {
    // create an authentication callback handler
    ClientCallbackHandler client_callback_handler = new ClientCallbackHandler(login_conf);

    // login our user
    Login login = null;/* ww  w  .j  a  v  a  2 s  .c om*/
    try {
        // specify a configuration object to be used
        Configuration.setConfiguration(login_conf);
        // now login
        login = new Login(AuthUtils.LOGIN_CONTEXT_CLIENT, client_callback_handler);
    } catch (LoginException ex) {
        LOG.error("Server failed to login in principal:" + ex, ex);
        throw new RuntimeException(ex);
    }

    final Subject subject = login.getSubject();
    if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) { // error
        throw new RuntimeException("Fail to verify user principal with section \""
                + AuthUtils.LOGIN_CONTEXT_CLIENT + "\" in login configuration file " + login_conf);
    }

    final String principal = StringUtils.isBlank(asUser) ? getPrincipal(subject) : asUser;
    String serviceName = AuthUtils.get(login_conf, AuthUtils.LOGIN_CONTEXT_CLIENT, "serviceName");
    if (serviceName == null) {
        serviceName = AuthUtils.SERVICE;
    }
    Map<String, String> props = new TreeMap<String, String>();
    props.put(Sasl.QOP, "auth");
    props.put(Sasl.SERVER_AUTH, "false");

    LOG.debug("SASL GSSAPI client transport is being established");
    final TTransport sasalTransport = new TSaslClientTransport(KERBEROS, principal, serviceName, serverHost,
            props, null, transport);

    // open Sasl transport with the login credential
    try {
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
            public Void run() {
                try {
                    LOG.debug("do as:" + principal);
                    sasalTransport.open();
                } catch (Exception e) {
                    LOG.error(
                            "Client failed to open SaslClientTransport to interact with a server during session initiation: "
                                    + e,
                            e);
                }
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new RuntimeException(e);
    }

    return sasalTransport;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {//from  www .ja  v  a 2s.  com
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}

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

@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token = null;/*from  w w  w  .  jav a 2s  .  c o  m*/
    String authorization = request
            .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION);

    if (authorization == null || !authorization
            .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) {
        return null;
    } else {
        authorization = authorization.substring(
                org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length())
                .trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        final String serverName = request.getServerName();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    GSSCredential gssCreds = null;
                    try {
                        gssCreds = gssManager.createCredential(
                                gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName),
                                        KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")),
                                GSSCredential.INDEFINITE_LIFETIME,
                                new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"),
                                        KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") },
                                GSSCredential.ACCEPT_ONLY);
                        gssContext = gssManager.createContext(gssCreds);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = base64.encodeToString(serverToken);
                            response.setHeader(
                                    org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE,
                                    org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE
                                            + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            log.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            KerberosName kerberosName = new KerberosName(clientPrincipal);
                            String userName = kerberosName.getShortName();
                            token = new AuthenticationToken(userName, clientPrincipal, getType());
                            response.setStatus(HttpServletResponse.SC_OK);
                            log.trace("SPNEGO completed for principal [%s]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                        if (gssCreds != null) {
                            gssCreds.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}

From source file:org.jolokia.jvmagent.handler.JolokiaHttpHandler.java

private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) {
    try {//from  w  ww.j av a  2s .  c o  m
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
            public Void run() throws IOException {
                doHandle(pHttpExchange);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new SecurityException("Security exception: " + e.getCause(), e.getCause());
    }
}

From source file:com.cloudera.alfredo.server.KerberosAuthenticationHandler.java

/**
 * Initializes the authentication handler instance.
 * <p/>// www  .  ja  va2 s .  c o  m
 * It creates a Kerberos context using the principal and keytab specified in the configuration.
 * <p/>
 * This method is invoked by the {@link AuthenticationFilter#init} method.
 *
 * @param config configuration properties to initialize the handler.
 *
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override
public void init(Properties config) throws ServletException {
    try {
        principal = config.getProperty(PRINCIPAL, principal);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        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>());

        KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, principal);

        loginContext = new LoginContext("", subject, null, kerberosConfiguration);
        loginContext.login();

        Subject serverSubject = loginContext.getSubject();
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
        LOG.info("Initialized, principal [{}] from keytab [{}]", principal, keytab);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}