List of usage examples for javax.servlet.http HttpServletRequest getScheme
public String getScheme();
From source file:csiro.pidsvc.mappingstore.action.ActionProxy.java
@Override public void run() { HttpClient httpClient = new DefaultHttpClient(); try {//from w ww. j a v a 2 s . c om HttpServletRequest originalHttpRequest = _controller.getRequest(); HttpServletResponse originalHttpResponse = _controller.getResponse(); HttpGet httpGet = new HttpGet(getExpandedActionValue()); if (isTraceMode()) trace(httpGet.getRequestLine().toString()); // Pass-through HTTP headers. HashMap<String, String> hmHeaders = _controller.getHttpHeaders(); for (String header : hmHeaders.keySet()) { httpGet.addHeader(header, hmHeaders.get(header)); if (isTraceMode()) trace("\t" + header + ": " + hmHeaders.get(header)); } // Handle X-Original-URI HTTP header. if (!hmHeaders.containsKey("X-Original-URI")) { String originalUri = originalHttpRequest.getScheme() + "://" + originalHttpRequest.getServerName(); if (originalHttpRequest.getServerPort() != 80) originalUri += ":" + originalHttpRequest.getServerPort(); originalUri += _controller.getUri().getOriginalUriAsString(); httpGet.addHeader("X-Original-URI", originalUri); if (isTraceMode()) trace("\tX-Original-URI: " + originalUri); } // Get the data. HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (isTraceMode()) trace(response.getStatusLine().toString()); // Pass HTTP headers through. if (!isTraceMode()) originalHttpResponse.setStatus(response.getStatusLine().getStatusCode()); if (entity.getContentType() != null) { if (isTraceMode()) { trace("\tContent-Type: " + entity.getContentType().getValue()); trace("\tContent-Length: " + EntityUtils.toString(entity).getBytes().length); } else originalHttpResponse.setContentType(entity.getContentType().getValue()); } String headerName; for (Header header : response.getAllHeaders()) { headerName = header.getName(); if (headerName.equalsIgnoreCase("Expires") || headerName.equalsIgnoreCase("Cache-Control") || headerName.equalsIgnoreCase("Content-Type") || headerName.equalsIgnoreCase("Set-Cookie") || headerName.equalsIgnoreCase("Transfer-Encoding")) continue; if (isTraceMode()) trace("\t" + header.getName() + ": " + header.getValue()); else originalHttpResponse.addHeader(header.getName(), header.getValue()); } // Pass content through. if (!isTraceMode()) originalHttpResponse.getWriter().write(EntityUtils.toString(entity)); } catch (Exception e) { _logger.trace("Exception occurred while proxying HTTP request.", e); if (isTraceMode()) { Throwable cause = e.getCause(); trace("Set response status: 500; exception: " + (cause == null ? e.getMessage() : cause.getMessage())); } else Http.returnErrorCode(_controller.getResponse(), 500, e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.aimluck.eip.modules.actions.ALSessionValidator.java
/** * * @param data//from w w w .ja v a 2s . c om * @throws Exception */ @Override public void doPerform(RunData data) throws Exception { try { super.doPerform(data); } catch (Throwable other) { setOrgParametersForError(data); data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR)); return; } // not login and can not connect database if (checkDbError(data)) { setOrgParametersForError(data); data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE); return; } // ? // Cookie?ID???????? if (data.getRequest().isRequestedSessionIdFromURL()) { JetspeedLink jsLink = JetspeedLinkFactory.getInstance(data); String url = jsLink.getHomePage().toString().replaceAll(";.*", ""); data.setRedirectURI(url); return; } JetspeedUser loginuser = (JetspeedUser) data.getUser(); if (isLogin(loginuser)) { try { JetspeedSecurityCache.load(loginuser.getUserName()); } catch (Exception e1) { // login and can not connect database String message = e1.getMessage(); if (message != null && message.indexOf(ALConstants.DB_ERROR_DETECT) != -1) { setOrgParametersForError(data); String template = data.getParameters().get("template"); if (template.endsWith("DBError")) { data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE); } else { ALEipUtils.redirectDBError(data); } return; } } } if (ALSessionUtils.isImageRequest(data)) { if (isLogin(loginuser)) { return; } } if (ALSessionUtils.isJsonScreen(data)) { if (isLogin(loginuser)) { return; } } if (data.getRequest().getAttribute(ALDigestAuthenticationFilter.REQUIRE_DIGEST_AUTH) != null) { HttpServletRequest hreq = data.getRequest(); HttpServletResponse hres = data.getResponse(); if (!isLogin(loginuser)) { String auth = hreq.getHeader("Authorization"); if (auth == null) { requireAuth(hres); return; } else { try { String decoded = decodeAuthHeader(auth); int pos = decoded.indexOf(":"); String username = decoded.substring(0, pos); String password = decoded.substring(pos + 1); JetspeedUser juser = JetspeedSecurity.login(username, password); if (juser != null && "F".equals(juser.getDisabled())) { JetspeedSecurity.saveUser(juser); } else { requireAuth(hres); return; } } catch (RuntimeException ex) { // RuntimeException requireAuth(hres); return; } catch (Exception ex) { requireAuth(hres); return; } } } if (isICalRequest(data)) { data.setScreenTemplate("ScheduleiCalScreen"); return; } else { hres.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } Context context = org.apache.turbine.services.velocity.TurbineVelocity.getContext(data); // for switching theme org by org setOrgParameters(data, context); // for preventing XSS on user name context.put("utils", new ALCommonUtils()); context.put("l10n", ALLocalizationUtils.createLocalization(data)); // Cookie????????? if (!isLogin(loginuser) && !data.getParameters().get("template").equals("CookieError")) { String username = data.getParameters().getString("username", ""); String password = data.getParameters().getString("password", ""); if (username.length() > 0) { if (ALCellularUtils.isSmartPhone(data) && "admin".equals(username)) { data.setUser(JetspeedSecurity.getAnonymousUser()); data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_LOGIN_ONLY_PC")); data.getUser().setHasLoggedIn(Boolean.FALSE); } else { try { loginuser = JetspeedSecurity.login(username, password); if (loginuser != null && "F".equals(loginuser.getDisabled())) { JetspeedSecurity.saveUser(loginuser); } else { data.setUser(JetspeedSecurity.getAnonymousUser()); data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_INVALIDATION_USER")); data.getUser().setHasLoggedIn(Boolean.FALSE); } } catch (LoginException e) { } } } } String externalLoginUrl = ALConfigService.get(Property.EXTERNAL_LOGIN_URL); boolean isScreenTimeout = false; if (!isLogin(loginuser) && JetspeedResources.getBoolean("automatic.logon.enable", false)) { if (data.getRequest().getCookies() != null) { String userName = data.getCookies().getString("username", ""); String loginCookieValue = data.getCookies().getString("logincookie", ""); if (userName.length() > 0 && loginCookieValue.length() > 0) { try { loginuser = JetspeedSecurity.getUser(userName); if (loginuser.getPerm("logincookie", "").equals(loginCookieValue)) { data.setUser(loginuser); loginuser.setHasLoggedIn(Boolean.TRUE); loginuser.updateLastLogin(); data.save(); } } catch (LoginException noSuchUser) { } catch (org.apache.jetspeed.services.security.UnknownUserException unknownUser) { logger.warn("Username from the cookie was not found: " + userName); } catch (Exception other) { logger.error("ALSessionValidator.doPerform", other); } } } } else if (!isLogin(loginuser) && !JetspeedResources.getBoolean("automatic.logon.enable", false)) { // ? ????????? // ??????????? String uri = data.getRequest().getRequestURI().trim(); String template = data.getScreenTemplate(); Class<?> cls = null; try { cls = Class.forName( new StringBuffer().append("com.aimluck.eip.modules.screens.").append(template).toString()); } catch (Exception e) { cls = null; } String newTemplate = null; if (cls != null) { if (Class.forName("com.aimluck.eip.modules.screens.ALJSONScreen").isAssignableFrom(cls)) { newTemplate = "ALJSONTimeoutScreen"; } else if (Class.forName("com.aimluck.eip.modules.screens.ALVelocityScreen") .isAssignableFrom(cls)) { newTemplate = "ALVelocityTimeoutScreen"; } } if (newTemplate != null) { isScreenTimeout = true; data.setScreenTemplate(newTemplate); // ? if (data.getSession() != null) { try { data.getSession().invalidate(); } catch (IllegalStateException ex) { logger.debug("???????"); } } } else { String contextPath = ServletContextLocator.get().getContextPath(); if ("/".equals(contextPath)) { contextPath = ""; } String portalPath = contextPath + "/portal"; if (!uri.equals(portalPath + "/") && !uri.equals(portalPath)) { data.setScreenTemplate("Timeout"); if (!"".equals(externalLoginUrl)) { // ?? data.setRedirectURI(externalLoginUrl); } StringBuffer sb = new StringBuffer(uri); int count = 0; String key = null; Enumeration<?> enu = data.getRequest().getParameterNames(); if (enu.hasMoreElements()) { sb.append("?"); } while (enu.hasMoreElements()) { if (count != 0) { sb.append("&"); } key = (String) enu.nextElement(); sb.append(key).append("=").append(data.getRequest().getParameter(key)); count = count + 1; } if (data.getUser() != null) { data.getUser().setTemp("redirect", StringEscapeUtils.escapeHtml(sb.toString())); context.put("alEipUtils", new ALEipUtils()); context.put("alEipManager", ALEipManager.getInstance()); } // ? if (data.getSession() != null) { try { data.getSession().invalidate(); } catch (IllegalStateException ex) { logger.debug("???????"); } } } } } JetspeedRunData jdata = null; try { jdata = (JetspeedRunData) data; } catch (ClassCastException e) { logger.error("The RunData object does not implement the expected interface, " + "please verify the RunData factory settings", e); return; } String language = data.getRequest().getParameter("js_language"); if (null != language) { loginuser.setPerm("language", language); } CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil .getServiceByName(LocalizationService.SERVICE_NAME); Locale locale = locService.getLocale(data); if (locale == null) { locale = new Locale(TurbineResources.getString("locale.default.language", "en"), TurbineResources.getString("locale.default.country", "US")); } if (loginuser != null) { loginuser.setTemp("locale", locale); } String paramPortlet = jdata.getParameters().getString("js_peid"); if (paramPortlet != null && paramPortlet.length() > 0) { jdata.setJs_peid(paramPortlet); } // Ajax???????? if (!isScreenTimeout && !"".equals(externalLoginUrl)) { HttpServletRequest request = data.getRequest(); if (!isLogin(loginuser)) { StringBuilder buf = new StringBuilder(); buf.append(request.getScheme()).append("://").append(request.getServerName()); if (request.getServerPort() == 80 || request.getServerPort() == 443) { // } else { buf.append(":").append(request.getServerPort()); } buf.append(request.getRequestURI()); String queryString = request.getQueryString(); if (queryString != null && !"".equals(queryString)) { buf.append("?").append(queryString); } String url = buf.toString(); if (!url.equals(externalLoginUrl)) { data.setRedirectURI(externalLoginUrl); } } } if (isLogin(loginuser)) { ALPreExecuteService.migratePsml(data, context); boolean hasMessage = false; Map<String, Entry> portlets = ALEipUtils.getGlobalPortlets(data); Entry entry = portlets.get("Message"); if (entry != null) { if (entry.getId().equals(jdata.getJs_peid())) { hasMessage = true; } } String client = ALEipUtils.getClient(data); boolean push = (!"IPHONE".equals(client)) || hasMessage; HttpServletRequest request = ((JetspeedRunData) data).getRequest(); String requestUrl = request.getRequestURL().toString(); String checkActivityUrl = ALConfigService.get(Property.CHECK_ACTIVITY_URL); String interval = ALConfigService.get(Property.CHECK_ACTIVITY_INTERVAL); ALEipUser eipUser = ALEipUtils.getALEipUser(data); String orgId = Database.getDomainName(); String viewer = new StringBuilder(orgId).append(":").append(eipUser.getName().getValue()).toString(); ALGadgetContext gadgetContext = new ALGadgetContext(data, viewer, "1", "/", 0); String relayUrl = ALConfigService.get(Property.CHECK_ACTIVITY_RELAY_URL); String rpctoken = String.valueOf(System.nanoTime()); String checkUrl = new StringBuilder("".equals(checkActivityUrl) ? "check.html" : checkActivityUrl) .append("?").append("st=").append(gadgetContext.getSecureToken()).append("&parent=") .append(URLEncoder.encode(requestUrl, "utf-8")).append("&interval=").append(interval) .append("&push=").append(push ? 1 : 0).append("#rpctoken=").append(rpctoken).toString(); if (data.getSession() != null && Boolean.parseBoolean((String) data.getSession().getAttribute("changeToPc"))) { // PC? context.put("client", ALEipUtils.getClient(data)); } context.put("requestUrl", requestUrl); context.put("relayUrl", relayUrl); context.put("rpctoken", rpctoken); context.put("checkUrl", checkUrl); context.put("st", gadgetContext.getSecureToken()); context.put("hasAuthorityCustomize", ALEipUtils.getHasAuthority(data, context, ALAccessControlConstants.VALUE_ACL_UPDATE)); } }
From source file:com.adito.boot.Util.java
/** * Dump all request parameters and some other useful stuff from * the request to {@link System#err}/*from w w w . j a v a2 s.c o m*/ * * @param request request to get parameters from */ public static void dumpRequest(HttpServletRequest request) { System.err.println("Context Path " + request.getContextPath()); System.err.println("Path Translated " + request.getPathTranslated()); System.err.println("Path Info " + request.getPathInfo()); System.err.println("Query: " + request.getQueryString()); System.err.println("Request URI: " + request.getRequestURI()); System.err.println("Request URL: " + request.getRequestURL()); System.err.println("Is Secure: " + request.isSecure()); System.err.println("Scheme: " + request.getScheme()); dumpRequestParameters(request); dumpRequestAttributes(request); dumpRequestHeaders(request); }
From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java
/** * Make sure directory forwarding happens when all conditions are met. * * @throws IOException on error//from w ww. j a v a2s. co m * @throws ServletException on error * @throws GenieException on error */ @Test public void canHandleForwardJobOutputRequestWithSuccess() throws IOException, ServletException, GenieException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final String forwardedFrom = null; final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response); final String jobHostName = UUID.randomUUID().toString(); Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName); //Mock parts of the http request final String http = "http"; Mockito.when(request.getScheme()).thenReturn(http); final int port = 8080; Mockito.when(request.getServerPort()).thenReturn(port); final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString(); Mockito.when(request.getRequestURI()).thenReturn(requestURI); final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT); Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames)); Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); //Mock parts of forward response final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class); final StatusLine statusLine = Mockito.mock(StatusLine.class); Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine); final int successCode = 200; Mockito.when(statusLine.getStatusCode()).thenReturn(successCode); final Header contentTypeHeader = Mockito.mock(Header.class); Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE); Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE); Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader }); final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString(); final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(UTF_8)); final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.getContent()).thenReturn(bis); Mockito.when(forwardResponse.getEntity()).thenReturn(entity); final ByteArrayServletOutputStream bos = new ByteArrayServletOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(bos); final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class); final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class); Mockito.when(clientHttpRequest.execute()) .thenReturn(new MockClientHttpResponse(text.getBytes(UTF_8), HttpStatus.OK)); Mockito.when(clientHttpRequest.getHeaders()).thenReturn(new HttpHeaders()); Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest); final RestTemplate template = new RestTemplate(factory); final Registry registry = Mockito.mock(Registry.class); final Counter counter = Mockito.mock(Counter.class); Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter); final JobRestController jobController = new JobRestController(Mockito.mock(JobCoordinatorService.class), this.jobSearchService, Mockito.mock(AttachmentService.class), Mockito.mock(ApplicationResourceAssembler.class), Mockito.mock(ClusterResourceAssembler.class), Mockito.mock(CommandResourceAssembler.class), Mockito.mock(JobResourceAssembler.class), Mockito.mock(JobRequestResourceAssembler.class), Mockito.mock(JobExecutionResourceAssembler.class), Mockito.mock(JobSearchResultResourceAssembler.class), this.hostname, template, this.genieResourceHttpRequestHandler, this.jobsProperties, registry); jobController.getJobOutput(jobId, forwardedFrom, request, response); Assert.assertThat(new String(bos.toByteArray(), UTF_8), Matchers.is(text)); Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT); Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId)); Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt()); Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response); }
From source file:io.druid.security.kerberos.KerberosAuthenticator.java
@Override public Filter getFilter() { return new AuthenticationFilter() { private Signer mySigner; @Override/*ww w .j a v a2 s.c om*/ public void init(FilterConfig filterConfig) throws ServletException { ClassLoader prevLoader = Thread.currentThread().getContextClassLoader(); try { // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader. // In case of druid since the class is actually loaded as an extension and filter init is done in main thread. // We need to set the classloader explicitly to extension class loader. Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader()); super.init(filterConfig); String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; Properties config = getConfiguration(configPrefix, filterConfig); String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET); if (signatureSecret == null) { signatureSecret = Long.toString(new Random().nextLong()); log.warn("'signature.secret' configuration not set, using a random value as secret"); } final byte[] secretBytes = StringUtils.toUtf8(signatureSecret); SignerSecretProvider signerSecretProvider = new SignerSecretProvider() { @Override public void init(Properties config, ServletContext servletContext, long tokenValidity) throws Exception { } @Override public byte[] getCurrentSecret() { return secretBytes; } @Override public byte[][] getAllSecrets() { return new byte[][] { secretBytes }; } }; mySigner = new Signer(signerSecretProvider); } finally { Thread.currentThread().setContextClassLoader(prevLoader); } } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper @Override protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException { AuthenticationToken token = null; String tokenStr = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) { tokenStr = cookie.getValue(); try { tokenStr = mySigner.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } break; } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (!token.getType().equals(getAuthenticationHandler().getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (token.isExpired()) { throw new AuthenticationException("AuthenticationToken expired"); } } return token; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; // If there's already an auth result, then we have authenticated already, skip this. if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) { filterChain.doFilter(request, response); return; } if (loginContext == null) { initializeKerberosLogin(); } String path = ((HttpServletRequest) request).getRequestURI(); if (isExcluded(path)) { filterChain.doFilter(request, response); } else { String clientPrincipal = null; try { Cookie[] cookies = httpReq.getCookies(); if (cookies == null) { clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request); } else { clientPrincipal = null; for (Cookie cookie : cookies) { if ("hadoop.auth".equals(cookie.getName())) { Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue()); if (matcher.matches()) { clientPrincipal = matcher.group(1); break; } } } } } catch (Exception ex) { clientPrincipal = null; } if (clientPrincipal != null) { request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(clientPrincipal, authorizerName, null)); } } doFilterSuper(request, response, filterChain); } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { boolean unauthorizedResponse = true; int errCode = HttpServletResponse.SC_UNAUTHORIZED; AuthenticationException authenticationEx = null; HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; boolean isHttps = "https".equals(httpRequest.getScheme()); try { boolean newToken = false; AuthenticationToken token; try { token = getToken(httpRequest); } catch (AuthenticationException ex) { log.warn("AuthenticationToken ignored: " + ex.getMessage()); // will be sent back in a 401 unless filter authenticates authenticationEx = ex; token = null; } if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) { if (token == null) { if (log.isDebugEnabled()) { log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest)); } token = getAuthenticationHandler().authenticate(httpRequest, httpResponse); if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) { token.setExpires(System.currentTimeMillis() + getValidity() * 1000); } newToken = true; } if (token != null) { unauthorizedResponse = false; if (log.isDebugEnabled()) { log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest), token.getUserName()); } final AuthenticationToken authToken = token; httpRequest = new HttpServletRequestWrapper(httpRequest) { @Override public String getAuthType() { return authToken.getType(); } @Override public String getRemoteUser() { return authToken.getUserName(); } @Override public Principal getUserPrincipal() { return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; } }; if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) { String signedToken = mySigner.sign(token.toString()); createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps); } doFilter(filterChain, httpRequest, httpResponse); } } else { unauthorizedResponse = false; } } catch (AuthenticationException ex) { // exception from the filter itself is fatal errCode = HttpServletResponse.SC_FORBIDDEN; authenticationEx = ex; if (log.isDebugEnabled()) { log.debug("Authentication exception: " + ex.getMessage(), ex); } else { log.warn("Authentication exception: " + ex.getMessage()); } } if (unauthorizedResponse) { if (!httpResponse.isCommitted()) { createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps); // If response code is 401. Then WWW-Authenticate Header should be // present.. reset to 403 if not found.. if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) { errCode = HttpServletResponse.SC_FORBIDDEN; } if (authenticationEx == null) { // Don't send an error response here, unlike the base AuthenticationFilter implementation. // This request did not use Kerberos auth. // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow // other Authenticator implementations to check the request. filterChain.doFilter(request, response); } else { // Do send an error response here, we attempted Kerberos authentication and failed. httpResponse.sendError(errCode, authenticationEx.getMessage()); } } } } }; }
From source file:com.irets.datadownloader.SearchPropertyServlet.java
public String getUrl3(HttpServletRequest req) { String scheme = req.getScheme(); // http String serverName = req.getServerName(); // hostname.com int serverPort = req.getServerPort(); // 80 String contextPath = req.getContextPath(); // /mywebapp // String servletPath = req.getServletPath(); // /servlet/MyServlet // String pathInfo = req.getPathInfo(); // /a/b;c=123 // String queryString = req.getQueryString(); // d=789 // Reconstruct original requesting URL String url = scheme + "://" + serverName + ":" + serverPort + contextPath;//+servletPath; // if (pathInfo != null) { // url += pathInfo; // }//from w ww . j a v a 2s . c o m // if (queryString != null) { // url += "?"+queryString; // } return url; }
From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java
/** * URL?./*from www .ja v a 2 s . c o m*/ * @return URL */ public String getBasePath() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); return String.format(BASE_PATH, request.getScheme(), SystemConfig.getValue(KEY_SERVER_NAME), getPort(request), request.getContextPath()); }
From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java
@Override public Filter getFilter() { return new AuthenticationFilter() { private Signer mySigner; @Override// w ww.j a va 2 s .c om public void init(FilterConfig filterConfig) throws ServletException { ClassLoader prevLoader = Thread.currentThread().getContextClassLoader(); try { // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader. // In case of druid since the class is actually loaded as an extension and filter init is done in main thread. // We need to set the classloader explicitly to extension class loader. Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader()); super.init(filterConfig); String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; Properties config = getConfiguration(configPrefix, filterConfig); String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET); if (signatureSecret == null) { signatureSecret = Long.toString(ThreadLocalRandom.current().nextLong()); log.warn("'signature.secret' configuration not set, using a random value as secret"); } final byte[] secretBytes = StringUtils.toUtf8(signatureSecret); SignerSecretProvider signerSecretProvider = new SignerSecretProvider() { @Override public void init(Properties config, ServletContext servletContext, long tokenValidity) { } @Override public byte[] getCurrentSecret() { return secretBytes; } @Override public byte[][] getAllSecrets() { return new byte[][] { secretBytes }; } }; mySigner = new Signer(signerSecretProvider); } finally { Thread.currentThread().setContextClassLoader(prevLoader); } } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper @Override protected AuthenticationToken getToken(HttpServletRequest request) throws AuthenticationException { AuthenticationToken token = null; String tokenStr = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) { tokenStr = cookie.getValue(); try { tokenStr = mySigner.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } break; } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (!token.getType().equals(getAuthenticationHandler().getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (token.isExpired()) { throw new AuthenticationException("AuthenticationToken expired"); } } return token; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; // If there's already an auth result, then we have authenticated already, skip this. if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) { filterChain.doFilter(request, response); return; } if (loginContext == null) { initializeKerberosLogin(); } String path = ((HttpServletRequest) request).getRequestURI(); if (isExcluded(path)) { filterChain.doFilter(request, response); } else { String clientPrincipal = null; try { Cookie[] cookies = httpReq.getCookies(); if (cookies == null) { clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request); } else { clientPrincipal = null; for (Cookie cookie : cookies) { if ("hadoop.auth".equals(cookie.getName())) { Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue()); if (matcher.matches()) { clientPrincipal = matcher.group(1); break; } } } } } catch (Exception ex) { clientPrincipal = null; } if (clientPrincipal != null) { request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(clientPrincipal, authorizerName, name, null)); } } doFilterSuper(request, response, filterChain); } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { boolean unauthorizedResponse = true; int errCode = HttpServletResponse.SC_UNAUTHORIZED; AuthenticationException authenticationEx = null; HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; boolean isHttps = "https".equals(httpRequest.getScheme()); try { boolean newToken = false; AuthenticationToken token; try { token = getToken(httpRequest); } catch (AuthenticationException ex) { log.warn("AuthenticationToken ignored: " + ex.getMessage()); // will be sent back in a 401 unless filter authenticates authenticationEx = ex; token = null; } if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) { if (token == null) { if (log.isDebugEnabled()) { log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest)); } token = getAuthenticationHandler().authenticate(httpRequest, httpResponse); if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) { token.setExpires(System.currentTimeMillis() + getValidity() * 1000); } newToken = true; } if (token != null) { unauthorizedResponse = false; if (log.isDebugEnabled()) { log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest), token.getUserName()); } final AuthenticationToken authToken = token; httpRequest = new HttpServletRequestWrapper(httpRequest) { @Override public String getAuthType() { return authToken.getType(); } @Override public String getRemoteUser() { return authToken.getUserName(); } @Override public Principal getUserPrincipal() { return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; } }; if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) { String signedToken = mySigner.sign(token.toString()); tokenToAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps); request.setAttribute(SIGNED_TOKEN_ATTRIBUTE, tokenToCookieString(signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps)); } // Since this request is validated also set DRUID_AUTHENTICATION_RESULT request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(token.getName(), authorizerName, name, null)); doFilter(filterChain, httpRequest, httpResponse); } } else { unauthorizedResponse = false; } } catch (AuthenticationException ex) { // exception from the filter itself is fatal errCode = HttpServletResponse.SC_FORBIDDEN; authenticationEx = ex; if (log.isDebugEnabled()) { log.debug(ex, "Authentication exception: " + ex.getMessage()); } else { log.warn("Authentication exception: " + ex.getMessage()); } } if (unauthorizedResponse) { if (!httpResponse.isCommitted()) { tokenToAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, false, isHttps); // If response code is 401. Then WWW-Authenticate Header should be // present.. reset to 403 if not found.. if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) { errCode = HttpServletResponse.SC_FORBIDDEN; } if (authenticationEx == null) { // Don't send an error response here, unlike the base AuthenticationFilter implementation. // This request did not use Kerberos auth. // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow // other Authenticator implementations to check the request. filterChain.doFilter(request, response); } else { // Do send an error response here, we attempted Kerberos authentication and failed. httpResponse.sendError(errCode, authenticationEx.getMessage()); } } } } }; }
From source file:org.alfresco.web.site.servlet.CSRFFilter.java
/** * Returns the current server's scheme, name & port * * @param request The http request//from ww w .j a v a2s .co m * @return the current server's scheme, name & port */ private String getServerString(HttpServletRequest request) { final String scheme = request.getScheme(); final int port = request.getServerPort(); String currentServerContext; if (("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443)) { currentServerContext = scheme + "://" + request.getServerName(); } else { currentServerContext = scheme + "://" + request.getServerName() + ':' + port; } return currentServerContext; }
From source file:org.encuestame.core.security.CustomAuthenticationEntryPoint.java
/** * *//* w w w . j av a2s .co m*/ @Override public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException { if (authException != null) { // you can check for the spefic exception here and redirect like // this logger.debug("respnse" + response.toString()); logger.debug("respnse" + response.getContentType()); logger.debug("request" + request.toString()); logger.debug("request" + request.getContentType()); //response.sendRedirect("403.html"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String redirectUrl = null; if (useForward) { if (forceHttps && "http".equals(request.getScheme())) { // First redirect the current request to HTTPS. // When that request is received, the forward to the login page // will be used. redirectUrl = buildHttpsRedirectUrlForRequest(httpRequest); } if (redirectUrl == null) { String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException); if (logger.isDebugEnabled()) { logger.debug("Server side forward to: " + loginForm); } RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm); dispatcher.forward(request, response); return; } } else { // redirect to login page. Use https if forceHttps true redirectUrl = buildRedirectUrlToLoginPage(httpRequest, httpResponse, authException); } redirectStrategy.sendRedirect(httpRequest, httpResponse, redirectUrl); }