List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED
int HTTP_UNAUTHORIZED
To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.
Click Source Link
From source file:org.jboss.aerogear.android.authentication.digest.DigestAuthenticationModuleRunner.java
@Override public HeaderAndBody onLogin(final String username, final String password) { HttpProvider provider = httpProviderFactory.get(loginURL, timeout); try {/*from ww w . ja va 2s .c o m*/ provider.get();// Should not be logged in and throw an exception throw new IllegalStateException("Login Called on service which was already logged in."); } catch (HttpException exception) { // If an exception occured that was not a failed login if (exception.getStatusCode() != HttpURLConnection.HTTP_UNAUTHORIZED) { throw exception; } Map<String, String> authenticateHeaders = DigestHeaderUtils .extractValues(exception.getHeaders().get(WWW_AUTHENTICATE_HEADER)); realm = authenticateHeaders.get(REALM); domain = authenticateHeaders.get(DOMAIN); nonce = authenticateHeaders.get(NONCE); algorithm = authenticateHeaders.get(ALGORITHM); qop = authenticateHeaders.get(QOP_OPTIONS); stale = authenticateHeaders.get(STALE); opaque = authenticateHeaders.get(OPAQUE); this.username = username; this.password = password; checkQop(qop); checkAlgorithm(algorithm); try { provider.setDefaultHeader("Authorization", getAuthorizationHeader(loginURL.toURI(), "GET", new byte[] {})); } catch (URISyntaxException ex) { Log.e(TAG, ex.getMessage(), ex); throw new RuntimeException(ex); } return provider.get(); } }
From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java
private OAuthSofunAccessToken doGetAccessToken(String consumerKey, String accessKey) throws OAuthException { // get is atomic OAuthSofunAccessToken ret = _getAccessToken(accessKey); if (ret == null) { throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "Token is invalid"); }//from w w w . ja v a 2 s .com if (!ret.getConsumer().getKey().equals(consumerKey)) { throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "Consumer is invalid"); } return ret; }
From source file:mobi.jenkinsci.ci.client.JenkinsHttpClient.java
public HttpResponse execute(final HttpRequestBase req) throws IOException { LOG.debug("Executing '" + req.getMethod() + " " + req.getURI() + "'"); if (!(httpClient instanceof JenkinsFormAuthHttpClient) && config.getUsername() != null && config.getUsername().trim().length() > 0) { ensurePreemptiveAuthRequest(req); }// ww w . j av a 2 s .c om HttpResponse response = httpContext == null ? httpClient.execute(req) : httpClient.execute(req, httpContext); if (response == null) { throw new IOException("Cannot contact URL " + req.getURI()); } final int responseStatus = response.getStatusLine().getStatusCode(); if ((responseStatus == HttpURLConnection.HTTP_UNAUTHORIZED || responseStatus == HttpURLConnection.HTTP_FORBIDDEN)) { req.releaseConnection(); httpClient = new JenkinsFormAuthHttpClient(httpClientFactory.getHttpClient(), config.getUrl(), config.getUsername(), config.getPassword(), req.getFirstHeader(Constants.X_AUTH_OTP_HEADER) != null ? req.getFirstHeader(Constants.X_AUTH_OTP_HEADER).getValue() : null); response = httpClient.execute(req); httpContext = null; } return elaborateResponse(response); }
From source file:org.wso2.carbon.registry.app.ResourceServlet.java
/** * Logic that will be executed for a get request. * * @param request the HTTP Servlet request. * @param response the HTTP Servlet response. * * @throws IOException if an error occurred. */// ww w.ja va2 s . c om protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String uri = request.getRequestURI(); int idx = uri.indexOf("resource"); String path = uri.substring(idx + 8); if (path == null) { String msg = "Could not get the resource content. Path is not specified."; log.error(msg); response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); return; } Resource resource; try { UserRegistry registry = Utils.getRegistry(request); try { path = new URI(path).normalize().toString(); } catch (URISyntaxException e) { log.error("Unable to normalize requested resource path: " + path, e); } String decodedPath = URLDecoder.decode(path, RegistryConstants.DEFAULT_CHARSET_ENCODING); CurrentSession.setUserRealm(registry.getUserRealm()); CurrentSession.setUser(registry.getUserName()); try { if (!AuthorizationUtils.authorize( RegistryUtils.getAbsolutePath(registry.getRegistryContext(), decodedPath), ActionConstants.GET)) { response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return; } resource = registry.get(decodedPath); } finally { CurrentSession.removeUserRealm(); CurrentSession.removeUser(); } } catch (AuthorizationFailedException e) { log.error(e.getMessage()); response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return; } catch (RegistryException e) { String msg = "Error retrieving the resource " + path + ". " + e.getMessage(); log.error(msg, e); throw e; } if (resource instanceof Collection) { String msg = "Could not get the resource content. Path " + path + " refers to a collection."; log.error(msg); response.setStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED); return; } // date based conditional get long ifModifiedSinceValue = request.getDateHeader("If-Modified-Since"); long lastModifiedValue = resource.getLastModified().getTime(); if (ifModifiedSinceValue > 0) { // convert the time values from milliseconds to seconds ifModifiedSinceValue /= 1000; lastModifiedValue /= 1000; /* condition to check we have latest updates in terms of dates */ if (ifModifiedSinceValue >= lastModifiedValue) { /* no need to response with data */ response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } response.setDateHeader("Last-Modified", lastModifiedValue); // eTag based conditional get String ifNonMatchValue = request.getHeader("if-none-match"); String currentETag = Utils.calculateEntityTag(resource); if (ifNonMatchValue != null) { if (ifNonMatchValue.equals(currentETag)) { /* the version is not modified */ response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } response.setHeader("ETag", currentETag); if (resource.getMediaType() != null && resource.getMediaType().length() > 0) { response.setContentType(resource.getMediaType()); } else { response.setHeader("Content-Disposition", "attachment; filename=" + RegistryUtils.getResourceName(path)); response.setContentType("application/download"); } InputStream contentStream = null; if (resource.getContent() != null) { contentStream = resource.getContentStream(); } if (contentStream != null) { try { ServletOutputStream servletOutputStream = response.getOutputStream(); byte[] contentChunk = new byte[RegistryConstants.DEFAULT_BUFFER_SIZE]; int byteCount; while ((byteCount = contentStream.read(contentChunk)) != -1) { servletOutputStream.write(contentChunk, 0, byteCount); } response.flushBuffer(); servletOutputStream.flush(); } finally { contentStream.close(); } } else { Object content = resource.getContent(); if (content != null) { if (content instanceof byte[]) { ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write((byte[]) content); response.flushBuffer(); servletOutputStream.flush(); } else { PrintWriter writer = response.getWriter(); writer.write(content.toString()); writer.flush(); } } } resource.discard(); } catch (RegistryException e) { String msg = "Failed to get resource content. " + e.getMessage(); log.error(msg, e); response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingUsingHttpURLConnection() throws Exception { final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/ping"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); String errorMessage = IOUtils.toString(conn.getErrorStream()); Assert.assertTrue(errorMessage.contains("Authentication required")); }
From source file:org.apache.hive.service.server.TestHS2HttpServerPam.java
@Test public void testUnauthorizedConnection() throws Exception { String baseURL = "http://" + host + ":" + webUIPort + "/stacks"; URL url = new URL(baseURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); }
From source file:pl.datamatica.traccar.api.metadata.model.LocalOrRemoteImeiNumber.java
private void initializeDeviceModelAndIsValid() { if (shouldCheckImeiRemotely()) { try {//from w w w. j a va 2s . c o m URL myURL = new URL(imeiModelCheckURL); HttpURLConnection connection = (HttpURLConnection) myURL.openConnection(); connection.setRequestProperty("Authorization", "Basic " + HttpHeaders.getEncodedCredentials(imeiManagerUser, imeiManagerPassword)); connection.setRequestMethod("GET"); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { isImeiValid = true; deviceModel = getRequestResponse(connection); } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { logger.error("IMEI manager can't check IMEI remotely, authorization failed." + " Check user, password, and privileges to resource management."); } } catch (MalformedURLException mue) { logger.error( "IMEI manager can't check IMEI remotely because of malformed URL: " + mue.getMessage()); } catch (IOException ioe) { logger.error("IMEI manager can't check IMEI remotely: " + ioe.getMessage()); } } else { ImeiNumber imeiNum = imeiProvider.getImeiByImeiString(imeiStr); if (imeiNum != null && !imeiNum.getIsDeleted()) { isImeiValid = true; deviceModel = imeiNum.getDeviceModel(); } } }
From source file:rapture.kernel.Login.java
public CallingContext checkLogin(String context, String username, String saltedPassword, ApiVersion clientApiVersion) {//w w w . j ava2 s . c om long functionStartTime = System.currentTimeMillis(); String documentName = "session/" + context; String content; if (!ApiVersionComparator.INSTANCE.isCompatible(clientApiVersion)) { String message = String.format("Client API Version (%s) does not match server API Version (%s)", clientApiVersion, ServerApiVersion.getApiVersion()); throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, message); } content = getEphemeralRepo().getDocument(documentName); CallingContext savedContext = JacksonUtil.objectFromJson(content, CallingContext.class); RaptureUser userAccount = Kernel.getAdmin().getUser(ContextFactory.getKernelUser(), username); String userPassInvalid = String.format("username or password invalid (attempted username '%s')", username); if (userAccount == null) { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, userPassInvalid); } if (username.equals(savedContext.getUser())) { if (userAccount.getInactive()) { String message = "Cannot login as an inactive user"; throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, message); } if (!userAccount.getVerified()) { String message = "This account has not yet been verified. Please check your email at " + userAccount.getEmailAddress() + " for the verification link.-"; throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, message); } if (userAccount.getApiKey()) { savedContext.setValid(true); } else { String toHash = userAccount.getHashPassword() + ":" + savedContext.getSalt(); String testHash = MD5Utils.hash16(toHash); if (testHash.equals(saltedPassword)) { savedContext.setValid(true); String msg = "User " + username + " logged in"; log.info(msg); Kernel.writeComment(msg); } else { RaptureException raptException = RaptureExceptionFactory .create(HttpURLConnection.HTTP_UNAUTHORIZED, userPassInvalid); log.info( RaptureExceptionFormatter.getExceptionMessage(raptException, "Passwords do not match")); throw raptException; } } } getEphemeralRepo().addToStage(RaptureConstants.OFFICIAL_STAGE, documentName, JacksonUtil.jsonFromObject(savedContext), false); getEphemeralRepo().commitStage(RaptureConstants.OFFICIAL_STAGE, "admin", "session validation"); // user has successfully logged in, lets write it to the audit logs Kernel.getAudit().getTrusted().writeAuditEntry(savedContext, RaptureConstants.DEFAULT_AUDIT_URI, "login", 0, String.format("User [%s] has logged in", username)); long endFunctionTime = System.currentTimeMillis(); Kernel.getMetricsService().recordTimeDifference("apiMetrics.loginApi.checkLogin.fullFunctionTime.succeeded", (endFunctionTime - functionStartTime)); return savedContext; }
From source file:web.kz.rhq.modules.plugins.jbossas7.ASConnection.java
private boolean isAuthorizationFailureResponse(int responseCode) { return responseCode == HttpURLConnection.HTTP_UNAUTHORIZED || responseCode == HTTP_TEMPORARY_REDIRECT; }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testNotAuthorizedEmptyTokenGetTTL() throws IOException { AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class); AccessToken accessToken = Mockito.mock(AccessToken.class); Mockito.when(authClient.getAccessToken()).thenReturn(accessToken); Mockito.when(accessToken.getValue()).thenReturn(StringUtils.EMPTY); Mockito.when(accessToken.getTokenType()).thenReturn("Bearer"); streamClient = RestStreamClient.builder(testServerHost, testServerPort).authClient(authClient).build(); try {//from w w w . j a v a 2 s . c o m streamClient.getTTL(TestUtils.AUTH_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode()); } }