Example usage for java.net HttpURLConnection HTTP_FORBIDDEN

List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_FORBIDDEN.

Prototype

int HTTP_FORBIDDEN

To view the source code for java.net HttpURLConnection HTTP_FORBIDDEN.

Click Source Link

Document

HTTP Status-Code 403: Forbidden.

Usage

From source file:com.yahoo.athenz.example.ntoken.HttpExampleClient.java

public static void main(String[] args) throws MalformedURLException, IOException {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain");
    String serviceName = cmd.getOptionValue("service");
    String privateKeyPath = cmd.getOptionValue("pkey");
    String keyId = cmd.getOptionValue("keyid");
    String url = cmd.getOptionValue("url");

    // we need to generate our principal credentials (ntoken). In
    // addition to the domain and service names, we need the
    // the service's private key and the key identifier - the
    // service with the corresponding public key must already be
    // registered in ZMS

    PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath));
    ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName,
            privateKey, keyId);// w ww  . j a  v  a2s.  c om
    Principal principal = identityProvider.getIdentity(domainName, serviceName);

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // set our Athenz credentials. The authority in the principal provides
    // the header name that we must use for credentials while the principal
    // itself provides the credentials (ntoken).

    con.setRequestProperty(principal.getAuthority().getHeader(), principal.getCredentials());

    // now process our request

    int responseCode = con.getResponseCode();
    switch (responseCode) {
    case HttpURLConnection.HTTP_FORBIDDEN:
        System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        System.out.println("Successful response: ");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        }
        break;
    default:
        System.out.println("Request failed - response status code: " + responseCode);
    }
}

From source file:com.yahoo.athenz.example.ztoken.HttpExampleClient.java

public static void main(String[] args) throws MalformedURLException, IOException {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain");
    String serviceName = cmd.getOptionValue("service");
    String privateKeyPath = cmd.getOptionValue("pkey");
    String keyId = cmd.getOptionValue("keyid");
    String url = cmd.getOptionValue("url");
    String ztsUrl = cmd.getOptionValue("ztsurl");
    String providerDomain = cmd.getOptionValue("provider-domain");
    String providerRole = cmd.getOptionValue("provider-role");

    // we need to generate our principal credentials (ntoken). In
    // addition to the domain and service names, we need the
    // the service's private key and the key identifier - the
    // service with the corresponding public key must already be
    // registered in ZMS

    PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath));
    ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName,
            privateKey, keyId);/*from  w w  w .  j  a  v  a 2s .  co  m*/

    // now we need to retrieve a role token (ztoken) for accessing
    // the provider Athenz enabled service

    RoleToken roleToken = null;
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl, domainName, serviceName, identityProvider)) {
        roleToken = ztsClient.getRoleToken(providerDomain, providerRole);
    }

    if (roleToken == null) {
        System.out.println(
                "Unable to retrieve role token for: " + providerRole + " in domain: " + providerDomain);
        System.exit(1);
    }

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // set our Athenz credentials. The ZTSClient provides the header
    // name that we must use for authorization token while the role
    // token itself provides the token string (ztoken).

    System.out.println("Using RoleToken: " + roleToken.getToken());
    con.setRequestProperty(ZTSClient.getHeader(), roleToken.getToken());

    // now process our request

    int responseCode = con.getResponseCode();
    switch (responseCode) {
    case HttpURLConnection.HTTP_FORBIDDEN:
        System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        System.out.println("Successful response: ");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        }
        break;
    default:
        System.out.println("Request failed - response status code: " + responseCode);
    }
}

From source file:be.fedict.eid.dss.admin.portal.AccountingExportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    Identity identity = (Identity) httpSession.getAttribute("org.jboss.seam.security.identity");
    if (false == identity.hasRole("admin")) {
        response.sendError(HttpURLConnection.HTTP_FORBIDDEN, "no admin role");
        return;//from w  w  w  .j  a  v a 2  s . c o m
    }

    response.setContentType("text/csv");
    PrintWriter printWriter = response.getWriter();
    List<AccountingEntity> accountingEntities = this.accountingService.listAll();
    for (AccountingEntity accountingEntity : accountingEntities) {
        printWriter.print("\"");
        printWriter.print(accountingEntity.getDomain());
        printWriter.print("\",\"");
        printWriter.print(accountingEntity.getRequests());
        printWriter.println("\"");
    }
}

From source file:org.fedoraproject.eclipse.packager.bodhi.api.errors.BodhiClientLoginException.java

/**
 * /*w w  w.  j  av a2  s . c  om*/
 * @return {@code true} if the user was not allowed access (i.e. 403,
 *         Forbidden was returned).
 */
public boolean isInvalidCredentials() {
    // Comment from: [...]fedora/client/proxyclient.py
    // Check for auth failures
    // Note: old TG apps returned 403 Forbidden on authentication failures.
    // Updated apps return 401 Unauthorized
    // We need to accept both until all apps are updated to return 401.
    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode == HttpURLConnection.HTTP_FORBIDDEN
            || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        // wrong username or password
        return true;
    }
    // some other, perhaps inconclusive? error
    return false;
}

From source file:org.apache.geronimo.testsuite.security.test.GenericRealmTest.java

/**
 * Test 3  /*from w ww .  ja va  2s  . c o  m*/
 * Test valid but forbidden user "alan"(role "it") cannot access the protected resources
 */
@Test
public void GenericFailureTest() throws Exception {
    Assert.assertEquals(getHTTPResponseStatus("alan"), HttpURLConnection.HTTP_FORBIDDEN);
}

From source file:org.cytoscape.app.internal.net.server.ScreenOriginsBeforeResponseTest.java

@Test
public void testScreenOrigins() throws Exception {
    final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2609));
    final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl();
    httpd.addResponder(new CyHttpResponder() {
        public Pattern getURIPattern() {
            return Pattern.compile("^/test$");
        }//w  w w  .  ja  v  a  2 s . c  o m

        public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) {
            return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html");
        }
    });
    httpd.addBeforeResponse(new ScreenOriginsBeforeResponse("http://x", "http://y"));
    httpd.start();

    HttpURLConnection connection = null;
    final String url = "http://localhost:2609/test";

    connection = connectToURL(url, "GET", null);
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN);

    connection = connectToURL(url, "GET", "http://x");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);

    connection = connectToURL(url, "GET", "http://y");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK);

    connection = connectToURL(url, "GET", "http://z");
    assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN);

    httpd.stop();
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.GerritPluginChecker.java

/**
 * Given a status code, decode its status.
 * @param statusCode HTTP code//w  w  w  .  j  ava 2s . com
 * @param pluginName plugin that was checked.
 * @return true/false if installed or not.
 */
private static boolean decodeStatus(int statusCode, String pluginName) {
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
        logger.info(Messages.PluginInstalled(pluginName));
        return true;
    case HttpURLConnection.HTTP_NOT_FOUND:
        logger.info(Messages.PluginNotInstalled(pluginName));
        return false;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        logger.warn(
                Messages.PluginHttpConnectionUnauthorized(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    case HttpURLConnection.HTTP_FORBIDDEN:
        logger.warn(Messages.PluginHttpConnectionForbidden(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    default:
        logger.warn(Messages.PluginHttpConnectionGeneralError(pluginName,
                Messages.HttpConnectionError(statusCode)));
        return false;
    }
}

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithSSL.java

@Test
public void testTraceIsDisabled() throws Exception {
    final URL url = new URL("https://" + SERVER_HOST + ":" + webServerPort);
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.trustStore", Resources.getResource("cacerts.jks").getPath());
    System.setProperties(systemProps);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("TRACE");
    Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
}

From source file:org.apache.geronimo.testsuite.servlets.ServletsTest.java

/**
 * Test2/*  w w w  .j av a 2 s .co m*/
 */
@Test
public void test_SampleServlet1_GET_Fail() throws Exception {
    Assert.assertEquals(invoke("/SampleServlet1", "GET", "alan", "starcraft"),
            HttpURLConnection.HTTP_FORBIDDEN);
}

From source file:org.peterbaldwin.vlcremote.net.ServerConnectionTest.java

@Override
protected void onPostExecute(Integer result) {
    switch (result) {
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        Toast.makeText(context, R.string.server_unauthorized, Toast.LENGTH_SHORT).show();
        break;//from   www.  ja  v  a2  s  .com
    case HttpURLConnection.HTTP_FORBIDDEN:
        Toast.makeText(context, R.string.server_forbidden, Toast.LENGTH_SHORT).show();
        break;
    case HttpURLConnection.HTTP_OK:
        Toast.makeText(context, R.string.server_ok, Toast.LENGTH_SHORT).show();
        break;
    default:
        Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show();
    }
}