List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED
int SC_UNAUTHORIZED
To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.
Click Source Link
From source file:it.smartcommunitylab.aac.controller.ResourceAccessController.java
@ApiOperation(value = "Get token info") @RequestMapping(method = RequestMethod.GET, value = "/resources/token") @Deprecated//from w w w.ja v a2s .c om public @ResponseBody AACTokenValidation getTokenInfo(HttpServletRequest request, HttpServletResponse response) { AACTokenValidation result = new AACTokenValidation(); try { String parsedToken = it.smartcommunitylab.aac.common.Utils.parseHeaderToken(request); OAuth2Authentication auth = resourceServerTokenServices.loadAuthentication(parsedToken); OAuth2AccessToken storedToken = tokenStore.getAccessToken(auth); long expiresIn = storedToken.getExpiresIn(); String clientId = auth.getOAuth2Request().getClientId(); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.ANY) .withSetterVisibility(JsonAutoDetect.Visibility.ANY) .withCreatorVisibility(JsonAutoDetect.Visibility.ANY)); String userName = null; String userId = null; boolean applicationToken = false; // System.err.println(auth.getPrincipal()); if (auth.getPrincipal() instanceof User) { User principal = (User) auth.getPrincipal(); userId = principal.getUsername(); // } if (auth.getPrincipal() instanceof it.smartcommunitylab.aac.model.User) { // it.smartcommunitylab.aac.model.User principal = (it.smartcommunitylab.aac.model.User)auth.getPrincipal(); // userId = principal.getId().toString(); // userName = getWSO2Name(user); } else { ClientDetailsEntity client = clientDetailsRepository.findByClientId(clientId); applicationToken = true; userId = "" + client.getDeveloperId(); // if (client.getParameters() != null) { // Map<String,?> parameters = mapper.readValue(client.getParameters(), Map.class); // userName = (String)parameters.get("username"); // } else { //// it.smartcommunitylab.aac.model.User user = userRepository.findOne(Long.parseLong(userId)); // userName = "admin"; // userName = (String)auth.getPrincipal(); // } } userName = userManager.getUserInternalName(Long.parseLong(userId)); result.setUsername(userName); result.setUserId(userId); result.setClientId(clientId); result.setScope(Iterables.toArray(auth.getOAuth2Request().getScope(), String.class)); result.setGrantType(auth.getOAuth2Request().getGrantType()); long now = System.currentTimeMillis(); result.setIssuedTime(now); result.setValidityPeriod(expiresIn); logger.info("Requested token " + parsedToken + " expires in " + result.getValidityPeriod()); result.setValid(true); result.setApplicationToken(applicationToken); // System.err.println(mapper.writeValueAsString(response)); } catch (InvalidTokenException e) { logger.error("Invalid token: " + e.getMessage()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } catch (Exception e) { logger.error("Error getting info for token: " + e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } return result; }
From source file:com.zimbra.cs.zimlet.ProxyServlet.java
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException { ZimbraLog.clearContext();//w w w . j ava 2 s . com boolean isAdmin = isAdminRequest(req); AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true); if (authToken == null) { String zAuthToken = req.getParameter(QP_ZAUTHTOKEN); if (zAuthToken != null) { try { authToken = AuthProvider.getAuthToken(zAuthToken); if (authToken.isExpired()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired"); return; } if (!authToken.isRegistered()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid"); return; } if (isAdmin && !authToken.isAdmin()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied"); return; } } catch (AuthTokenException e) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken"); return; } } } if (authToken == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie"); return; } // get the posted body before the server read and parse them. byte[] body = copyPostedData(req); // sanity check String target = req.getParameter(TARGET_PARAM); if (target == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // check for permission URL url = new URL(target); if (!isAdmin && !checkPermissionOnTarget(url, authToken)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // determine whether to return the target inline or store it as an upload String uploadParam = req.getParameter(UPLOAD_PARAM); boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true")); HttpMethod method = null; try { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); String reqMethod = req.getMethod(); if (reqMethod.equalsIgnoreCase("GET")) { method = new GetMethod(target); } else if (reqMethod.equalsIgnoreCase("POST")) { PostMethod post = new PostMethod(target); if (body != null) post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = post; } else if (reqMethod.equalsIgnoreCase("PUT")) { PutMethod put = new PutMethod(target); if (body != null) put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = put; } else if (reqMethod.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(target); } else { ZimbraLog.zimlet.info("unsupported request method: " + reqMethod); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // handle basic auth String auth, user, pass; auth = req.getParameter(AUTH_PARAM); user = req.getParameter(USER_PARAM); pass = req.getParameter(PASS_PARAM); if (auth != null && user != null && pass != null) { if (!auth.equals(AUTH_BASIC)) { ZimbraLog.zimlet.info("unsupported auth type: " + auth); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); client.setState(state); method.setDoAuthentication(true); } Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String hdr = (String) headers.nextElement(); ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr)); if (canProxyHeader(hdr)) { ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr)); if (hdr.equalsIgnoreCase("x-host")) method.getParams().setVirtualHost(req.getHeader(hdr)); else method.addRequestHeader(hdr, req.getHeader(hdr)); } } try { if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) { method.setFollowRedirects(true); } HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { ZimbraLog.zimlet.info("exception while proxying " + target, ex); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode(); // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line Header ctHeader = method.getResponseHeader("Content-Type"); String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue(); InputStream targetResponseBody = method.getResponseBodyAsStream(); if (asUpload) { String filename = req.getParameter(FILENAME_PARAM); if (filename == null || filename.equals("")) filename = new ContentType(contentType).getParameter("name"); if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null) filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()) .getParameter("filename"); if (filename == null || filename.equals("")) filename = "unknown"; List<Upload> uploads = null; if (targetResponseBody != null) { try { Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId()); uploads = Arrays.asList(up); } catch (ServiceException e) { if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED)) status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE; else status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } resp.setStatus(status); FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null); } else { resp.setStatus(status); resp.setContentType(contentType); for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName())) resp.addHeader(h.getName(), h.getValue()); if (targetResponseBody != null) ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true); } } finally { if (method != null) method.releaseConnection(); } }
From source file:com.mindquarry.webapp.servlet.AuthenticationFilter.java
/** * Filter method that implements the actual logic and decides whether to * process by calling the next filter in the chain (another filter or the * servlet) or stopping here and sending a special response (authentication * request or redirect).// w ww . j a va2 s.c o m * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { // cast to http request and response due to read and set http headers HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // always send an authentication request in order to avoid one round trip response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm_ + "\""); // only do authentication for protected URIs, eg. excluded login page if (isProtected(request)) { String authenticatedUser = authenticateUser(request); // the special login request is done to actually perform the // authentication, this is typically the second step initiated by // the login page if (isLoginRequest(request)) { if (authenticatedUser == null) { // not authenticated. trigger auth. with username / password // either by the HTTP auth dialog in the browser or // automatically by Javascript XMLHttpRequest response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else { // authenticated. redirect to original target String originalUrl = request.getParameter(TARGET_URI_PARAM); String redirectUrl = response.encodeRedirectURL((originalUrl != null ? originalUrl : ".")); response.sendRedirect(redirectUrl); } // no further servlet processing. return; } else { // 99 percent of all pages, not the special login request. // here we either have the first request to the server, ie. // not yet authenticated, or some client that does not send the // authorization data preemptively (although he already did // authenticate) -> see isGuiBrowserRequest() if (authenticatedUser == null) { // not authenticated. // standard browser with preemptive sending auth data, thus // it must be the first request -> go to login page if (isGuiBrowserRequest(request)) { String loginUrl = buildLoginUrlForRequest(request); String redirectUrl = response.encodeRedirectURL(loginUrl); response.sendRedirect(redirectUrl); } else { // trigger simple client auth. or re-authentication response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } // no further servlet processing. return; } else { // authenticated. make username available as request attribute request.setAttribute(USERNAME_ATTR, authenticatedUser); } } } // access granted, proceed with the servlet chain.doFilter(servletRequest, servletResponse); }
From source file:com.sun.syndication.propono.atom.server.AtomServlet.java
/** * Handles an Atom GET by calling handler and writing results to response. *//*www . ja va2 s .co m*/ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.debug("Entering"); AtomHandler handler = createAtomRequestHandler(req, res); String userName = handler.getAuthenticatedUsername(); if (userName != null) { AtomRequest areq = new AtomRequestImpl(req); try { if (handler.isAtomServiceURI(areq)) { // return an Atom Service document AtomService service = handler.getAtomService(areq); Document doc = service.serviceToDocument(); res.setContentType("application/atomsvc+xml; charset=utf-8"); Writer writer = res.getWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, writer); writer.close(); res.setStatus(HttpServletResponse.SC_OK); } else if (handler.isCategoriesURI(areq)) { Categories cats = handler.getCategories(areq); res.setContentType("application/xml"); Writer writer = res.getWriter(); Document catsDoc = new Document(); catsDoc.setRootElement(cats.categoriesToElement()); XMLOutputter outputter = new XMLOutputter(); outputter.output(catsDoc, writer); writer.close(); res.setStatus(HttpServletResponse.SC_OK); } else if (handler.isCollectionURI(areq)) { // return a collection Feed col = handler.getCollection(areq); col.setFeedType(FEED_TYPE); WireFeedOutput wireFeedOutput = new WireFeedOutput(); Document feedDoc = wireFeedOutput.outputJDom(col); res.setContentType("application/atom+xml; charset=utf-8"); Writer writer = res.getWriter(); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(feedDoc, writer); writer.close(); res.setStatus(HttpServletResponse.SC_OK); } else if (handler.isEntryURI(areq)) { // return an entry Entry entry = handler.getEntry(areq); if (entry != null) { res.setContentType("application/atom+xml; type=entry; charset=utf-8"); Writer writer = res.getWriter(); Atom10Generator.serializeEntry(entry, writer); writer.close(); } else { res.setStatus(HttpServletResponse.SC_NOT_FOUND); } } else if (handler.isMediaEditURI(areq)) { AtomMediaResource entry = handler.getMediaResource(areq); res.setContentType(entry.getContentType()); res.setContentLength((int) entry.getContentLength()); Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream()); res.getOutputStream().flush(); res.getOutputStream().close(); } else { res.setStatus(HttpServletResponse.SC_NOT_FOUND); } } catch (AtomException ae) { res.sendError(ae.getStatus(), ae.getMessage()); log.debug("ERROR processing GET", ae); } catch (Exception e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); log.debug("ERROR processing GET", e); } } else { res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\""); res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } log.debug("Exiting"); }
From source file:org.openxdata.server.servlet.FormDownloadServlet.java
private void uploadData(HttpServletRequest request, HttpServletResponse response) throws IOException { byte status = OpenXDataConstants.STATUS_NULL; try {//from ww w . jav a 2 s .com if (OpenXDataConstants.TRUE_TEXT_VALUE .equalsIgnoreCase(request.getParameter(OpenXDataConstants.REQUEST_PARAM_BATCH_ENTRY))) { try { String serializerKey = request.getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER); XformSerializer formSerializer = serializationService.getFormSerializer(serializerKey); List<String> xforms = formSerializer.deSerialize(request.getInputStream(), getXforms()); if (xforms != null) { for (String xml : xforms) processForm(xml); status = OpenXDataConstants.STATUS_SUCCESS; } else { status = OpenXDataConstants.STATUS_FAILURE; formSerializer.serializeFailure(response.getOutputStream(), new Exception("No forms returned from the serializer")); log.warn("No forms returned by the serializer"); } } catch (Exception ex) { log.error(ex.getMessage(), ex); status = OpenXDataConstants.STATUS_FAILURE; } } else { User user = authenticationService.authenticate(request.getParameter("uname"), request.getParameter("pw")); if (user == null) response.sendError(HttpServletResponse.SC_UNAUTHORIZED); else { response.setContentType("text/html"); String form = getRequestAsString(request); processForm(form); } } } catch (Exception ex) { if (status == OpenXDataConstants.STATUS_NULL) { PrintWriter out = response.getWriter(); out.println("<HTML><HEAD><TITLE>Form Submission Status</TITLE>" + "</HEAD><BODY>Problem submitting form! <BR /> " + ex.getMessage() + "</BODY></HTML>"); out.close(); } } }
From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean running_state = CMS.isInRunningState(); if (!running_state) throw new IOException("CMS server is not ready to serve."); HttpServletRequest req = request;/*from w ww . j a v a2 s . c o m*/ HttpServletResponse resp = response; CMSRequest cmsRequest = newCMSRequest(); // set argblock cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request))); // set http request cmsRequest.setHttpReq(request); // set http response cmsRequest.setHttpResp(response); // set servlet config. cmsRequest.setServletConfig(mConfig); // set servlet context. cmsRequest.setServletContext(mConfig.getServletContext()); char[] content = null; String encodedreq = null; String method = null; int len = -1; IPKIMessage msg = null; IPKIMessage replymsg = null; // NOTE must read all bufer before redoing handshake for // ssl client auth for client auth to work. // get request method method = req.getMethod(); // get content length len = request.getContentLength(); // get content, a base 64 encoded serialized request. if (len > 0) { InputStream in = request.getInputStream(); InputStreamReader inreader = new InputStreamReader(in, "UTF8"); BufferedReader reader = new BufferedReader(inreader, len); content = new char[len]; int done = reader.read(content, 0, len); int total = done; while (done >= 0 && total < len) { done = reader.read(content, total, len - total); total += done; } reader.close(); encodedreq = new String(content); } // force client auth handshake, validate RA and get RA's Id. // NOTE must do this after all contents are read for ssl // redohandshake to work X509Certificate peerCert; try { peerCert = getPeerCert(req); } catch (EBaseException e) { mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT")); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } if (peerCert == null) { // XXX log something here. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // authenticate RA String RA_Id = null; String raUserId = null; IAuthToken token = null; try { token = authenticate(request); raUserId = token.getInString("userid"); RA_Id = peerCert.getSubjectDN().toString(); } catch (EInvalidCredentials e) { // already logged. resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } catch (EBaseException e) { // already logged. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN()); // authorize AuthzToken authzToken = null; try { authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit"); } catch (Exception e) { // do nothing for now } if (authzToken == null) { cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED); return; } // after cert validated, check http request. if (!method.equalsIgnoreCase("POST")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } if (len <= 0) { resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED); return; } // now process request. CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id); try { // decode request. msg = (IPKIMessage) mReqEncoder.decode(encodedreq); // process request replymsg = processRequest(RA_Id, raUserId, msg, token); } catch (IOException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (EBaseException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } catch (Exception e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); } CMS.debug("ConnectorServlet: done processRequest"); // encode reply try { String encodedrep = mReqEncoder.encode(replymsg); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/html"); resp.setContentLength(encodedrep.length()); // send reply OutputStream out = response.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8"); writer.write(encodedrep); writer.flush(); writer.close(); out.flush(); } catch (Exception e) { CMS.debug("ConnectorServlet: error writing e=" + e.toString()); } CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id); }
From source file:com.sg.rest.SpringSecurityTest.java
@Test public void testSecureResourceWithAuthTokenButForNonExistentAccount() throws IOException, Exception { String authToken = webSecurityService.generateToken(ACCOUNT_ID, Instant.now(), TokenExpirationStandardDurations.WEB_SESSION_TOKEN_EXPIRATION_DURATION); GetAccountRolesOperation request = new GetAccountRolesOperation(ACCOUNT_ID); when(handler.handle(new GetAccountRolesOperation(ACCOUNT_ID))) .thenReturn(new GetAccountRolesResponse(GetAccountRolesStatus.STATUS_ACCOUNT_NOT_FOUND)); mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST).header(HttpCustomHeaders.AUTH_TOKEN_HEADER.getHeader(), authToken)).andExpect(status().is(HttpServletResponse.SC_UNAUTHORIZED)) .andExpect(content().contentType(CustomMediaTypes.APPLICATION_JSON_UTF8.getMediatype())) .andExpect(jsonPath("$.eventRef.id", not(isEmptyOrNullString()))).andExpect(jsonPath("$.status", is(AuthentificationFailureStatus.TOKEN_AUTHENTICATION_ACCOUNT_DO_NOT_EXISTS.name()))); }
From source file:com.hortonworks.registries.auth.server.TestKerberosAuthenticationHandler.java
public void testRequestWithoutAuthorization() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Assert.assertNull(handler.authenticate(request, response)); Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); }
From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Communicates with redirect url and works as a transparent proxy * /*from ww w.java 2 s . co m*/ * @param request * the servlet request * @param response * the servlet response * @throws IOException * if an exception occurs */ private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpURLConnection httpCon = null; URL redirectURL = null; InputStream input = null; OutputStream output = null; InputStream proxyInput = null; OutputStream proxyOutput = null; try { input = request.getInputStream(); output = response.getOutputStream(); String sQueryStr = request.getQueryString(); String sAuthorization = request.getHeader("Authorization"); String requestBody = readInputCharacters(input); String requestMethod = request.getMethod(); String contentType = request.getContentType(); String encoding = request.getCharacterEncoding(); LOGGER.finer(" Request method = " + requestMethod); LOGGER.finer(" Query string = " + sQueryStr); LOGGER.finer(" Authorization header =" + sAuthorization); LOGGER.finer(" Character Encoding = " + encoding); LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr); redirectURL = new URL(this._redirectURL + "?" + sQueryStr); httpCon = (HttpURLConnection) redirectURL.openConnection(); httpCon.setDoInput(true); httpCon.setDoOutput(true); httpCon.setUseCaches(false); httpCon.setRequestMethod(requestMethod); httpCon.setRequestProperty("Content-type", contentType); if (sAuthorization != null) { httpCon.addRequestProperty("Authorization", sAuthorization); } proxyOutput = httpCon.getOutputStream(); send(requestBody, proxyOutput); String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate"); if (authenticateHdr != null) { LOGGER.finer(" WWW-Authenticate : " + authenticateHdr); response.setHeader("WWW-Authenticate", StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr))); } LOGGER.finer(" Response Code : " + httpCon.getResponseCode()); if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { proxyInput = httpCon.getInputStream(); send(proxyInput, output); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (proxyInput != null) { proxyInput.close(); } if (proxyOutput != null) { proxyOutput.close(); } if (httpCon != null) { httpCon.disconnect(); } } }
From source file:com.zimbra.cs.servlet.util.AuthUtil.java
public static Account basicAuthRequest(HttpServletRequest req, boolean allowGuest, boolean isDav) throws IOException, ServiceException, UserServletException { String auth = req.getHeader(HTTP_AUTH_HEADER); // TODO: more liberal parsing of Authorization value... if (auth == null || !auth.startsWith("Basic ")) { throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, "must authenticate"); }/*from ww w. j a v a 2s . com*/ // 6 comes from "Basic ".length(); String userPass = new String(Base64.decodeBase64(auth.substring(6).getBytes()), "UTF-8"); int loc = userPass.indexOf(":"); if (loc == -1) { throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST, "invalid basic auth credentials"); } String userPassedIn = userPass.substring(0, loc); String user = userPassedIn; String pass = userPass.substring(loc + 1); Provisioning prov = Provisioning.getInstance(); if (user.indexOf('@') == -1) { String host = HttpUtil.getVirtualHost(req); if (host != null) { Domain d = prov.get(Key.DomainBy.virtualHostname, host.toLowerCase()); if (d != null) user += "@" + d.getName(); } } Account acct = prov.get(AccountBy.name, user); if (acct == null) { if (allowGuest) { return new GuestAccount(user, pass); } throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, "invalid username/password"); } try { Map<String, Object> authCtxt = new HashMap<String, Object>(); authCtxt.put(AuthContext.AC_ORIGINATING_CLIENT_IP, ZimbraServlet.getOrigIp(req)); authCtxt.put(AuthContext.AC_REMOTE_IP, ZimbraServlet.getClientIp(req)); authCtxt.put(AuthContext.AC_ACCOUNT_NAME_PASSEDIN, userPassedIn); authCtxt.put(AuthContext.AC_USER_AGENT, req.getHeader("User-Agent")); Protocol proto = isDav ? Protocol.http_dav : Protocol.http_basic; prov.authAccount(acct, pass, proto, authCtxt); } catch (ServiceException se) { throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, "invalid username/password"); } return acct; }