Example usage for org.apache.hadoop.security.authentication.client PseudoAuthenticator USER_NAME

List of usage examples for org.apache.hadoop.security.authentication.client PseudoAuthenticator USER_NAME

Introduction

In this page you can find the example usage for org.apache.hadoop.security.authentication.client PseudoAuthenticator USER_NAME.

Prototype

String USER_NAME

To view the source code for org.apache.hadoop.security.authentication.client PseudoAuthenticator USER_NAME.

Click Source Link

Document

Name of the additional parameter that carries the 'user.name' value.

Usage

From source file:org.apache.falcon.request.BaseRequest.java

License:Apache License

public HttpResponse run()
        throws URISyntaxException, IOException, AuthenticationException, InterruptedException {
    URIBuilder uriBuilder = new URIBuilder(this.url);

    /*falcon now reads a user.name parameter in the request.
    by default we will add it to every request.*/
    uriBuilder.addParameter(PseudoAuthenticator.USER_NAME, this.user);
    uri = uriBuilder.build();/*from www  .j  av  a 2  s  .  c  o m*/
    this.url = uri.toString();
    // process the get
    if (this.method.equalsIgnoreCase("get")) {
        return execute(new HttpGet(this.url));
    } else if (this.method.equalsIgnoreCase("delete")) {
        return execute(new HttpDelete(this.url));
    }

    HttpEntityEnclosingRequest request = null;
    if (this.method.equalsIgnoreCase("post")) {
        request = new HttpPost(new URI(this.url));
    } else if (this.method.equalsIgnoreCase("put")) {
        request = new HttpPut(new URI(this.url));
    } else {
        throw new IOException("Unknown method: " + method);
    }
    if (this.requestData != null) {
        request.setEntity(new StringEntity(requestData));
    }
    return execute(request);
}

From source file:org.apache.falcon.resource.channel.HTTPChannel.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from w  w w .  j av a  2s. co  m
public <T> T invoke(String methodName, Object... args) throws FalconException {
    HttpServletRequest incomingRequest = null;
    try {
        Method method = getMethod(service, methodName, args);
        String urlPrefix = getFalconEndPoint();
        final String url = urlPrefix + "/" + pathValue(method, args);
        LOG.debug("Executing {}", url);

        incomingRequest = getIncomingRequest(args);
        incomingRequest.getInputStream().reset();
        String httpMethod = getHttpMethod(method);
        String mimeType = getConsumes(method);
        String accept = MediaType.WILDCARD;
        final String user = CurrentUser.getUser();

        String doAsUser = incomingRequest.getParameter(DO_AS_PARAM);
        WebResource resource = getClient().resource(UriBuilder.fromUri(url).build().normalize())
                .queryParam("user.name", user);
        if (doAsUser != null) {
            resource = resource.queryParam("doAs", doAsUser);
        }

        AuthenticatedURL.Token authenticationToken = null;
        if (SecurityUtil.isSecurityEnabled()) {
            UserGroupInformation ugiLoginUser = UserGroupInformation.getCurrentUser();
            LOG.debug("Security is enabled. Using DoAs : " + ugiLoginUser.getUserName());
            authenticationToken = ugiLoginUser.doAs(new PrivilegedExceptionAction<AuthenticatedURL.Token>() {
                @Override
                public AuthenticatedURL.Token run() throws Exception {
                    return getToken(url + PseudoAuthenticator.USER_NAME + "=" + user, getClient());
                }
            });
        }

        ClientResponse response = resource.header("Cookie", AUTH_COOKIE_EQ + authenticationToken).accept(accept)
                .type(mimeType).method(httpMethod, ClientResponse.class,
                        (isPost(httpMethod) ? incomingRequest.getInputStream() : null));
        incomingRequest.getInputStream().reset();

        Family status = response.getClientResponseStatus().getFamily();
        if (status == Family.INFORMATIONAL || status == Family.SUCCESSFUL) {
            return (T) response.getEntity(method.getReturnType());
        } else if (response.getClientResponseStatus().getStatusCode() == Response.Status.BAD_REQUEST
                .getStatusCode()) {
            LOG.error("Request failed: {}", response.getClientResponseStatus().getStatusCode());
            throw FalconWebException.newAPIException(response.getEntity(APIResult.class).getMessage());
        } else {
            LOG.error("Request failed: {}", response.getClientResponseStatus().getStatusCode());
            throw new FalconException(response.getEntity(String.class));
        }
    } catch (FalconWebException falconWebException) {
        LOG.error("Request failed", falconWebException);
        throw falconWebException;
    } catch (Throwable e) {
        LOG.error("Request failed", e);
        throw new FalconException(e);
    } finally {
        try {
            if (incomingRequest != null) {
                incomingRequest.getInputStream().reset();
            }
        } catch (IOException e) {
            LOG.error("Error in HTTPChannel", e);
        }
    }
}

From source file:org.apache.falcon.security.FalconAuthorizationToken.java

License:Apache License

private static void authenticate(String user, String protocol, String host, int port)
        throws IOException, AuthenticationException, InterruptedException {
    final URL url = new URL(String.format("%s://%s:%d/%s", protocol, host, port,
            AUTH_URL + "?" + PseudoAuthenticator.USER_NAME + "=" + user));
    LOGGER.info("Authorize using url: " + url.toString());

    final AuthenticatedURL.Token currentToken = new AuthenticatedURL.Token();

    /*using KerberosAuthenticator which falls back to PsuedoAuthenticator
    instead of passing authentication type from the command line - bad factory*/
    try {/*from ww w .  j  av  a  2s  .  co  m*/
        HttpsURLConnection.setDefaultSSLSocketFactory(BaseRequest.getSslContext().getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    HttpsURLConnection.setDefaultHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
    UserGroupInformation callerUGI = KerberosHelper.getUGI(user);
    callerUGI.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            new AuthenticatedURL(AUTHENTICATOR).openConnection(url, currentToken);
            return null;
        }
    });
    String key = getKey(user, protocol, host, port);

    // initialize a hash map if its null.
    LOGGER.info("Authorization Token: " + currentToken.toString());
    INSTANCE.tokens.put(key, currentToken);
}

From source file:org.apache.hcatalog.templeton.Server.java

License:Apache License

/**
 * Verify that we have a valid user.  Throw an exception if invalid.
 *///from  ww w  .j a v  a  2  s.c  o m
public void verifyUser() throws NotAuthorizedException {
    if (getUser() == null) {
        String msg = "No user found.";
        if (!UserGroupInformation.isSecurityEnabled())
            msg += "  Missing " + PseudoAuthenticator.USER_NAME + " parameter.";
        throw new NotAuthorizedException(msg);
    }
}

From source file:org.apache.hive.hcatalog.templeton.Server.java

License:Apache License

/**
 * Verify that we have a valid user.  Throw an exception if invalid.
 *///ww w. j a va2  s  .  co  m
public void verifyUser() throws NotAuthorizedException {
    String requestingUser = getRequestingUser();
    if (requestingUser == null) {
        String msg = "No user found.";
        if (!UserGroupInformation.isSecurityEnabled()) {
            msg += "  Missing " + PseudoAuthenticator.USER_NAME + " parameter.";
        }
        throw new NotAuthorizedException(msg);
    }
    if (doAs != null && !doAs.equals(requestingUser)) {
        /*if doAs user is different than logged in user, need to check that
        that logged in user is authorized to run as 'doAs'*/
        ProxyUserSupport.validate(requestingUser, getRequestingHost(requestingUser, request), doAs);
    }
}

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

License:Apache License

private static ClientResponse getClientResponse(String sqoopUrl, String sqoopApi, String userName) {
    ClientResponse response = null;// www .j  a  va2 s . co m
    String[] sqoopUrls = sqoopUrl.trim().split("[,;]");
    if (ArrayUtils.isEmpty(sqoopUrls)) {
        return null;
    }

    Client client = Client.create();

    for (String currentUrl : sqoopUrls) {
        if (StringUtils.isBlank(currentUrl)) {
            continue;
        }

        String url = currentUrl.trim() + sqoopApi + "?" + PseudoAuthenticator.USER_NAME + "=" + userName;
        try {
            response = getClientResponse(url, client);

            if (response != null) {
                if (response.getStatus() == HttpStatus.SC_OK) {
                    break;
                } else {
                    response.close();
                }
            }
        } catch (Throwable t) {
            String msgDesc = "Exception while getting sqoop response, sqoopUrl: " + url;
            LOG.error(msgDesc, t);
        }
    }
    client.destroy();

    return response;
}

From source file:org.apache.solr.security.hadoop.ImpersonationUtil.java

License:Apache License

static SolrRequest getProxyRequest(String user, String doAs) {
    return new CollectionAdminRequest.List() {
        @Override/*from   w w w. ja  v  a2 s . c  o m*/
        public SolrParams getParams() {
            ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());
            params.set(PseudoAuthenticator.USER_NAME, user);
            params.set(KerberosPlugin.IMPERSONATOR_DO_AS_HTTP_PARAM, doAs);
            return params;
        }
    };
}

From source file:org.apache.solr.security.hadoop.ImpersonatorCollectionsHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    called.set(true);/*from   w  w  w  .  ja  va2  s . co  m*/
    super.handleRequestBody(req, rsp);
    String doAs = req.getParams().get(KerberosPlugin.IMPERSONATOR_DO_AS_HTTP_PARAM);
    if (doAs != null) {
        HttpServletRequest httpRequest = (HttpServletRequest) req.getContext().get("httpRequest");
        Assert.assertNotNull(httpRequest);
        String user = req.getParams().get(PseudoAuthenticator.USER_NAME);
        Assert.assertNotNull(user);
        Assert.assertEquals(user, httpRequest.getAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME));
    }
}

From source file:org.apache.solr.security.hadoop.TestDelegationWithHadoopAuth.java

License:Apache License

private String getDelegationToken(final String renewer, final String user, HttpSolrClient solrClient)
        throws Exception {
    DelegationTokenRequest.Get get = new DelegationTokenRequest.Get(renewer) {
        @Override//w w  w .  j a  va 2 s.  com
        public SolrParams getParams() {
            ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());
            params.set(PseudoAuthenticator.USER_NAME, user);
            return params;
        }
    };
    DelegationTokenResponse.Get getResponse = get.process(solrClient);
    return getResponse.getDelegationToken();
}

From source file:org.apache.solr.security.hadoop.TestDelegationWithHadoopAuth.java

License:Apache License

private long renewDelegationToken(final String token, final int expectedStatusCode, final String user,
        HttpSolrClient client) throws Exception {
    DelegationTokenRequest.Renew renew = new DelegationTokenRequest.Renew(token) {
        @Override/*from  w w  w . java 2  s  . c o  m*/
        public SolrParams getParams() {
            ModifiableSolrParams params = new ModifiableSolrParams(super.getParams());
            params.set(PseudoAuthenticator.USER_NAME, user);
            return params;
        }

        @Override
        public Set<String> getQueryParams() {
            Set<String> queryParams = super.getQueryParams();
            queryParams.add(PseudoAuthenticator.USER_NAME);
            return queryParams;
        }
    };
    try {
        DelegationTokenResponse.Renew renewResponse = renew.process(client);
        assertEquals(HttpStatus.SC_OK, expectedStatusCode);
        return renewResponse.getExpirationTime();
    } catch (HttpSolrClient.RemoteSolrException ex) {
        assertEquals(expectedStatusCode, ex.code());
        return -1;
    }
}