List of usage examples for javax.servlet.http HttpServletRequest isSecure
public boolean isSecure();
From source file:ru.org.linux.search.SearchController.java
@RequestMapping(value = "/search.jsp", method = { RequestMethod.GET, RequestMethod.HEAD }) public String search(HttpServletRequest request, Model model, @ModelAttribute("query") SearchRequest query, BindingResult bindingResult) throws Exception { Map<String, Object> params = model.asMap(); boolean initial = query.isInitial(); if (!initial && !bindingResult.hasErrors()) { if (!query.getQ().equals(query.getOldQ())) { query.setSection(null);//from ww w .j a va 2 s . c o m query.setGroup(0); } query.setOldQ(query.getQ()); if (query.getQ().trim().isEmpty()) { return "redirect:/search.jsp"; } SearchViewer sv = new SearchViewer(query); if (query.getGroup() != 0) { Group group = groupDao.getGroup(query.getGroup()); if ("wiki".equals(query.getSection()) || group.getSectionId() != Integer.valueOf(query.getSection())) { query.setGroup(0); } } QueryResponse response = sv.performSearch(solrServer); long current = System.currentTimeMillis(); SolrDocumentList list = response.getResults(); Collection<SearchItem> res = new ArrayList<SearchItem>(list.size()); for (SolrDocument doc : list) { res.add(new SearchItem(doc, userDao, msgbaseDao, lorCodeService, request.isSecure())); } FacetField sectionFacet = response.getFacetField("section"); if (sectionFacet != null && sectionFacet.getValueCount() > 1) { params.put("sectionFacet", buildSectionFacet(sectionFacet)); } else if (sectionFacet != null && sectionFacet.getValueCount() == 1) { Count first = sectionFacet.getValues().get(0); query.setSection(first.getName()); } FacetField groupFacet = response.getFacetField("group_id"); if (groupFacet != null && groupFacet.getValueCount() > 1) { params.put("groupFacet", buildGroupFacet(query.getSection(), groupFacet)); } long time = System.currentTimeMillis() - current; params.put("result", res); params.put("searchTime", response.getElapsedTime()); params.put("numFound", list.getNumFound()); if (list.getNumFound() > query.getOffset() + SearchViewer.SEARCH_ROWS) { params.put("nextLink", "/search.jsp?" + query.getQuery(query.getOffset() + SearchViewer.SEARCH_ROWS)); } if (query.getOffset() - SearchViewer.SEARCH_ROWS >= 0) { params.put("prevLink", "/search.jsp?" + query.getQuery(query.getOffset() - SearchViewer.SEARCH_ROWS)); } params.put("time", time); } return "search"; }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testPassiveLoginPkiUnsupportedPost() throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException { String samlRequest = authNRequestPassivePkiPost; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); Subject subject = mock(Subject.class); PrincipalCollection principalCollection = mock(PrincipalCollection.class); SecurityAssertion securityAssertion = mock(SecurityAssertion.class); SecurityToken securityToken = mock(SecurityToken.class); SecurityManager securityManager = mock(SecurityManager.class); when(subject.getPrincipals()).thenReturn(principalCollection); when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion)); when(securityAssertion.getSecurityToken()).thenReturn(securityToken); //this mock element is what will cause the signature error when(securityToken.getToken()).thenReturn(mock(Element.class)); when(securityManager.getSubject(anyObject())).thenReturn(subject); idpEndpoint.setSecurityManager(securityManager); idpEndpoint.setStrictSignature(false); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert/*from w ww .jav a 2s .c om*/ when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request); String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse\" value=\"", "\" />"); responseStr = new String(Base64.getDecoder().decode(responseStr)); //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp assertThat(responseStr, containsString("status:RequestUnsupported")); }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testPassiveLoginPkiUnsupported() throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException { String samlRequest = authNRequestPassivePkiGet; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); Subject subject = mock(Subject.class); PrincipalCollection principalCollection = mock(PrincipalCollection.class); SecurityAssertion securityAssertion = mock(SecurityAssertion.class); SecurityToken securityToken = mock(SecurityToken.class); SecurityManager securityManager = mock(SecurityManager.class); when(subject.getPrincipals()).thenReturn(principalCollection); when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion)); when(securityAssertion.getSecurityToken()).thenReturn(securityToken); //this mock element is what will cause the signature error when(securityToken.getToken()).thenReturn(mock(Element.class)); when(securityManager.getSubject(anyObject())).thenReturn(subject); idpEndpoint.setSecurityManager(securityManager); idpEndpoint.setStrictSignature(false); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert//from w w w .ja va2 s . co m when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature, request); String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse=", "&RelayState"); responseStr = URLDecoder.decode(responseStr, "UTF-8"); responseStr = RestSecurity.inflateBase64(responseStr); //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp assertThat(responseStr, containsString("status:RequestUnsupported")); }
From source file:eu.eidas.node.AbstractNodeServlet.java
/** * Sets HTTPOnly Header on the session to prevent cookies from being accessed through * client-side script.//ww w . j a v a2 s .c o m * * @param renewSession indicates that the session cookie will be renewed */ protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request, HttpServletResponse response) { if (request != null && request.getSession(false) != null) { // Renewing the session if necessary String currentSession = null; String messageLog = null; if (renewSession) { currentSession = sessionIdRegenerationInWebApp(request); messageLog = "http session Renewed : {}"; } else { currentSession = request.getSession().getId(); messageLog = "http session obtained from request : {}"; } MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession); getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession); // changing session cookie to http only cookie if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) { //Session Id requested by the client, obtained from the cookie final String requestedSessionId = request.getRequestedSessionId(); for (Cookie cookie : request.getCookies()) { getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]", cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue()); if (currentSession.equals(requestedSessionId)) { // Removes old version boolean isSecure = request.isSecure(); getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}", cookie.toString()); getLogger().debug("Is using SSL?", isSecure); //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header // //NOSONAR cookie.setMaxAge(0); //NOSONAR cookie.setPath(getServletContext().getContextPath()); //NOSONAR cookie.setDomain(request.getServerName()); //NOSONAR cookie.setSecure(isSecure); //NOSONAR cookie.setHttpOnly(true); //NOSONAR response.addCookie(cookie); // Create new one httpOnly StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName()) .append(EIDASValues.EQUAL.toString()).append(cookie.getValue()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString()) .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString()) .append(" ").append(EIDASValues.PATH.toString()) .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString()) .append(isSecure ? EIDASValues.SECURE.toString() : ""); response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString()); } } } //cookie _csrf // request.setAttribute("_csrf_header", "X-CSRF-TOKEN"); // UUID idOne = UUID.randomUUID(); // LOG.info("generate csrf id="+idOne); // request.setAttribute("_csrf", idOne); response.setHeader("_csrf_header", "X-CSRF-TOKEN"); UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo); Cookie gato = new Cookie("_csrf", idOne.toString()); response.addCookie(gato); response.setHeader("X-CSRF-TOKEN", idTwo.toString()); } else { getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !"); } }
From source file:de.sainth.recipe.backend.security.AuthFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String header = request.getHeader("Authorization"); Optional<Cookie> cookie; if (request.getCookies() != null) { cookie = Arrays.stream(request.getCookies()).filter(c -> COOKIE_NAME.equals(c.getName())).findFirst(); } else {/*from www. j av a2s. com*/ cookie = Optional.empty(); } if (!cookie.isPresent() && (header == null || header.length() == 0)) { throw new AccessDeniedException("No authentication information present"); } RecipeManagerAuthenticationToken authentication; try { if (cookie.isPresent()) { authentication = parseToken(cookie.get().getValue()); } else { Optional<RecipeManagerAuthenticationToken> maybeAuthentication; if (header.startsWith("Bearer ")) { maybeAuthentication = parseBearerToken(header); } else { maybeAuthentication = parseBasicAuth(header); } if (maybeAuthentication.isPresent()) { authentication = maybeAuthentication.get(); } else { throw new AccessDeniedException("Bad credentials"); } } } catch (ExpiredJwtException | SignatureException e) { throw new AccessDeniedException("Token not valid"); } SecurityContextHolder.getContext().setAuthentication(authentication); response.addCookie(createCookie(authentication, request.isSecure())); chain.doFilter(request, response); }
From source file:com.almende.eve.transport.http.AgentServlet.java
/** * Handle session.//w ww. j av a2s . c o m * * @param req * the req * @param res * the res * @return true, if successful * @throws IOException * Signals that an I/O exception has occurred. */ private boolean handleSession(final HttpServletRequest req, final HttpServletResponse res) throws IOException { try { if (req.getSession(false) != null) { return true; } final Handshake hs = doHandShake(req); if (hs.equals(Handshake.INVALID)) { return false; } String doAuthenticationStr = AgentListener.getParam("eve_authentication"); if (doAuthenticationStr == null) { // TODO: authentication param is deprecated since v2.0. Cleanup // some day doAuthenticationStr = AgentListener.getParam("authentication"); if (doAuthenticationStr == null) { doAuthenticationStr = "true"; LOG.warning("context-param \"eve_authentication\" not found. Using default value " + doAuthenticationStr); } else { LOG.warning( "context-param \"authentication\" is deprecated. Use \"eve_authentication\" instead."); } } final Boolean doAuthentication = Boolean.parseBoolean(doAuthenticationStr); if (hs.equals(Handshake.NAK) && doAuthentication) { if (!req.isSecure()) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request needs to be secured with SSL for session management!"); return false; } if (!req.authenticate(res)) { return false; } } // generate new session: req.getSession(true); } catch (final Exception e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Exception running HandleSession:" + e.getMessage()); LOG.log(Level.WARNING, "", e); return false; } return true; }
From source file:com.boylesoftware.web.impl.AbstractRouterConfiguration.java
@Override public String getRouteURI(final HttpServletRequest request, final String routeId, final URIType type, final String... uriParams) { // find mapping final RouteImpl mapping = this.mappingsById.get(routeId); if (mapping == null) throw new IllegalArgumentException("No mapping for route id " + routeId + "."); // check number of provided URI parameters final int numURIParams = mapping.getNumURIParams(); if (numURIParams != uriParams.length) throw new IllegalArgumentException( "Number of URI parameters does" + " not match the route mapping's URI pattern."); // build the URI try (final PooledStringBuffer buf = StringBufferPool.get()) { // build server root relative URI final String uriTmpl = mapping.getURITemplate(); final String relativeURI = (numURIParams > 0 ? this.replaceURIPlaceholders(uriTmpl, uriParams, buf) : uriTmpl);/* w w w. j a v a2s. c o m*/ // determine if SSL is needed final boolean needsSSL = ((type == URIType.FORCE_SSL) || (type == URIType.FORCE_ABSOLUTE_SSL) || ((type == URIType.DEFAULT) && ((mapping.getSecurityMode() != SecurityMode.DEFAULT) || this.isAuthenticationRequired(relativeURI)))); // is server root relative URI OK? final boolean secureRequest = request.isSecure(); final boolean authedRequest = (request.getAttribute(Attributes.AUTHED_USER) != null); if ((type != URIType.FORCE_ABSOLUTE_PLAIN) && (type != URIType.FORCE_ABSOLUTE_SSL) && ((!needsSSL && !(secureRequest && ((type == URIType.FORCE_PLAIN) || !authedRequest))) || (needsSSL && secureRequest))) return relativeURI; // build full URL final StringBuilder urlSB = buf.getStringBuilder(); urlSB.setLength(0); if (needsSSL) urlSB.append("https://"); else urlSB.append("http://"); urlSB.append(request.getServerName()); final int httpsPort = this.webapp.getHTTPSPort(); final int httpPort = this.webapp.getHTTPPort(); if (needsSSL && (httpsPort != 443)) urlSB.append(':').append(httpsPort); else if (!needsSSL && (httpPort != 80)) urlSB.append(':').append(httpPort); urlSB.append(relativeURI); // return it return urlSB.toString(); } }
From source file:ru.org.linux.topic.UncommitedTopicsController.java
@RequestMapping public ModelAndView viewAll( @RequestParam(value = "section", required = false, defaultValue = "0") int sectionId, HttpServletRequest request, HttpServletResponse response) { Template tmpl = Template.getTemplate(request); ModelAndView modelAndView = new ModelAndView("view-all"); Section section = null;/* w w w .ja v a2s . c o m*/ if (sectionId != 0) { section = sectionService.getSection(sectionId); modelAndView.addObject("section", section); modelAndView.addObject("addlink", AddTopicController.getAddUrl(section)); } response.setDateHeader("Expires", new Date(System.currentTimeMillis() - 20 * 3600 * 1000).getTime()); response.setDateHeader("Last-Modified", new Date(System.currentTimeMillis() - 120 * 1000).getTime()); String title; switch (sectionId) { case Section.SECTION_NEWS: title = "? ?"; break; case Section.SECTION_POLLS: title = "? ?"; break; case Section.SECTION_GALLERY: title = "? ?"; break; case 0: title = "? ?"; break; default: title = "?: " + section.getName(); break; } modelAndView.addObject("title", title); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.MONTH, -3); List<Topic> messages = topicListService.getAllTopicsFeed(section, calendar.getTime()); modelAndView.addObject("messages", prepareService.prepareMessagesForUser(messages, request.isSecure(), tmpl.getCurrentUser(), tmpl.getProf(), false)); List<TopicListDto.DeletedTopic> deleted = topicListService.getDeletedTopics(sectionId, !tmpl.isModeratorSession()); modelAndView.addObject("deletedTopics", deleted); modelAndView.addObject("sections", sectionService.getSectionList()); return modelAndView; }
From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.WorkflowHandlerHelper.java
public static void zippedFolder(HttpServletRequest p_request, HttpServletResponse p_response, long companyId, Set<Long> jobIdSet, Set<File> exportListFiles, Set<String> locales) { String zipFileName = AmbFileStoragePathUtils.getReportsDir(companyId) + File.separator + ReportConstants.REPORT_QA_CHECKS_REPORT + ".zip"; File zipFile = new File(zipFileName); Map<File, String> entryFileToFileNameMap = getEntryFileToFileNameMap(exportListFiles, jobIdSet, locales, AmbFileStoragePathUtils.getReportsDir(companyId).getPath() + File.separator + ReportConstants.REPORT_QA_CHECKS_REPORT); try {/*from ww w . j ava 2 s. co m*/ ZipIt.addEntriesToZipFile(zipFile, entryFileToFileNameMap, ""); String downloadFileName = zipFile.getName(); if (entryFileToFileNameMap.entrySet().size() > 0) { if (jobIdSet != null && jobIdSet.size() == 1) { Long jobId = jobIdSet.iterator().next(); downloadFileName = ReportConstants.REPORT_QA_CHECKS_REPORT + "_(" + jobId + ").zip"; } else if (jobIdSet != null && jobIdSet.size() > 1) { String tempS = jobIdSet.toString(); String jobNamesstr = tempS.substring(1, tempS.length() - 1); downloadFileName = ReportConstants.REPORT_QA_CHECKS_REPORT + "_(" + jobNamesstr + ").zip"; } } else { downloadFileName = "No Report Download.zip"; } // write zip file to client p_response.setContentType("application/zip"); p_response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\";"); if (p_request.isSecure()) { PageHandler.setHeaderForHTTPSDownload(p_response); } p_response.setContentLength((int) zipFile.length()); // Send the data to the client byte[] inBuff = new byte[4096]; FileInputStream fis = new FileInputStream(zipFile); int bytesRead = 0; while ((bytesRead = fis.read(inBuff)) != -1) { p_response.getOutputStream().write(inBuff, 0, bytesRead); } if (bytesRead > 0) { p_response.getOutputStream().write(inBuff, 0, bytesRead); } fis.close(); FileUtil.deleteFile(zipFile); } catch (Exception e) { logger.error(e); } finally { if (zipFile.exists()) zipFile.deleteOnExit(); } }