List of usage examples for javax.servlet.http Cookie setPath
public void setPath(String uri)
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
/** * Clear cookie.//from w w w . j ava 2 s .com * * @param key the key */ public void clearCookie(String key) { Cookie tsc = new Cookie(key, ""); tsc.setPath(getWikiWeb().getContextPath()); // tsc.setSecure(true); tsc.setMaxAge(0); response.addCookie(tsc); }
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
/** * set a cookie.//from w w w. ja va2 s . co m * * @param key the key * @param value the value */ @SuppressWarnings("deprecation") public void setCookie(String key, String value) { String cvalue = URLEncoder.encode(value); Cookie tsc = new Cookie(key, cvalue); tsc.setPath(getWikiWeb().getContextPath()); if (StringUtils.isEmpty(tsc.getPath()) == true) { tsc.setPath("/"); } tsc.setMaxAge((int) TimeInMillis.YEAR); response.addCookie(tsc); }
From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) { notNull(path, "Path"); if (requestBody != null && !multiParts.isEmpty()) { throw new IllegalStateException( "You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?"); }/*from www . jav a 2 s . com*/ String baseUri; if (isNotBlank(basePath)) { baseUri = mergeAndRemoveDoubleSlash(basePath, path); } else { baseUri = path; } final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri); if (!queryParams.isEmpty()) { new ParamApplier(queryParams) { @Override protected void applyParam(String paramName, String[] paramValues) { uriComponentsBuilder.queryParam(paramName, paramValues); } }.applyParams(); } String uri = uriComponentsBuilder.build().toUriString(); final MockHttpServletRequestBuilder request; if (multiParts.isEmpty()) { request = MockMvcRequestBuilders.request(method, uri, pathParams); } else if (method != POST) { throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST); } else { request = MockMvcRequestBuilders.fileUpload(uri, pathParams); } String requestContentType = findContentType(); if (!params.isEmpty()) { new ParamApplier(params) { @Override protected void applyParam(String paramName, String[] paramValues) { request.param(paramName, paramValues); } }.applyParams(); if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) { setContentTypeToApplicationFormUrlEncoded(request); } } if (!formParams.isEmpty()) { if (method == GET) { throw new IllegalArgumentException("Cannot use form parameters in a GET request"); } new ParamApplier(formParams) { @Override protected void applyParam(String paramName, String[] paramValues) { request.param(paramName, paramValues); } }.applyParams(); boolean isInMultiPartMode = isInMultiPartMode(request); if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) { setContentTypeToApplicationFormUrlEncoded(request); } } if (!attributes.isEmpty()) { new ParamApplier(attributes) { @Override protected void applyParam(String paramName, String[] paramValues) { request.requestAttr(paramName, paramValues[0]); } }.applyParams(); } if (RestDocsClassPathChecker.isSpringRestDocsInClasspath() && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) { request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri)); } if (StringUtils.isNotBlank(requestContentType)) { request.contentType(MediaType.parseMediaType(requestContentType)); } if (headers.exist()) { for (Header header : headers) { request.header(header.getName(), header.getValue()); } } if (cookies.exist()) { for (Cookie cookie : cookies) { javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); if (cookie.hasComment()) { servletCookie.setComment(cookie.getComment()); } if (cookie.hasDomain()) { servletCookie.setDomain(cookie.getDomain()); } if (cookie.hasMaxAge()) { servletCookie.setMaxAge(cookie.getMaxAge()); } if (cookie.hasPath()) { servletCookie.setPath(cookie.getPath()); } if (cookie.hasVersion()) { servletCookie.setVersion(cookie.getVersion()); } servletCookie.setSecure(cookie.isSecured()); request.cookie(servletCookie); } } if (!sessionAttributes.isEmpty()) { request.sessionAttrs(sessionAttributes); } if (!multiParts.isEmpty()) { MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request; for (MockMvcMultiPart multiPart : multiParts) { MockMultipartFile multipartFile; String fileName = multiPart.getFileName(); String controlName = multiPart.getControlName(); String mimeType = multiPart.getMimeType(); if (multiPart.isByteArray()) { multipartFile = new MockMultipartFile(controlName, fileName, mimeType, (byte[]) multiPart.getContent()); } else if (multiPart.isFile() || multiPart.isInputStream()) { InputStream inputStream; if (multiPart.isFile()) { try { inputStream = new FileInputStream((File) multiPart.getContent()); } catch (FileNotFoundException e) { return SafeExceptionRethrower.safeRethrow(e); } } else { inputStream = (InputStream) multiPart.getContent(); } try { multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream); } catch (IOException e) { return SafeExceptionRethrower.safeRethrow(e); } } else { // String multipartFile = new MockMultipartFile(controlName, fileName, mimeType, ((String) multiPart.getContent()).getBytes()); } multiPartRequest.file(multipartFile); } } if (requestBody != null) { if (requestBody instanceof byte[]) { request.content((byte[]) requestBody); } else if (requestBody instanceof File) { byte[] bytes = toByteArray((File) requestBody); request.content(bytes); } else { request.content(requestBody.toString()); } } logRequestIfApplicable(method, baseUri, path, pathParams); return performRequest(request); }
From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java
/** * This is the main method that does the authentication and should be * invoked by the classes that would like to open a new authentication * process against an HTTP Basic protected source. * <p>/*from ww w .j ava 2s . com*/ * The username and password for the source are assumed to be the ones * captured during the authentication. These are stored in creds and in * this case the root parameters. creds is an array of credentials for * all external sources. The first element is 'root' which contains the * credentials captured from the login page. This method reviews if there * is a credential id identical to the name associated to this module * in the config file. If so, these credentials are used to authenticate * against this HTTP Basic source, and if not 'root' one will be used * instead. * <p> * If the HTTP Basic authentication result is OK, it creates an * authentication cookie containing the HTTP Basic credentials * to be reused during authorization. The content returned back from the * remote secure backend system is sent as well. Anyway, the HTTP * response code is returned in this method to inform the caller on the * status. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param creds an array of credentials for all external sources * @param id the default credential id to be retrieved from creds * @return the HTTP error code * @throws HttpException * @throws IOException */ public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies, String url, Credentials creds, String id) throws HttpException, IOException { Cookie[] cookies = null; //Credentials UsernamePasswordCredentials credentials = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP Basic authentication start"); //First read the u/p the credentails store, in this case using the same as the root login logger.debug("HttpBasic: trying to get creds from repository ID: " + id); Credential httpBasicCred = null; try { httpBasicCred = creds.getCredential(id); } catch (NullPointerException npe) { logger.error("NPE while reading credentials of ID: " + id); } if (httpBasicCred != null) { credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } else { logger.debug("HttpBasic: trying to get creds from repository \"root\""); httpBasicCred = creds.getCredential("root"); if (httpBasicCred != null) { logger.info("Trying with root credentails"); credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } } logger.debug("Authenticating"); Header[] headers = null; HttpMethodBase method = null; //Get Max connections int maxConnectionsPerHost = 30; int maxTotalConnections = 100; //Cookie Max Age int authMaxAge = -1; try { maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue(); maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue(); authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:"); logger.error(" * maxConnectionsPerHost * maxTotalConnections * authMaxAge"); } // Protection if (webProcessor == null) { // Instantiate Web processor if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) { webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections); } else { webProcessor = new WebProcessor(); } } // // Launch the authentication process // // A fixed URL in the repository that all users have access to which can be used to authN a user // and capture the HTTP Authorization Header String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage"); try { // Set HTTP headers headers = new Header[1]; // Set User-Agent headers[0] = new Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5"); // Request page, testing if credentials are valid if (credentials != null) { logger.debug("Username: " + credentials.getUserName()); logger.debug("URL: " + authURL); } //HTTP request method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL); //Read the auth header and store in the cookie, the authZ class will use this later headers = method.getRequestHeaders(); Header authHeader = null; authHeader = method.getRequestHeader("Authorization"); // Cache status code if (method != null) statusCode = method.getStatusCode(); if (statusCode == HttpServletResponse.SC_OK) { //Authentication worked, so create the auth cookie to indicate it has worked Cookie extAuthCookie = null; extAuthCookie = new Cookie(BASIC_COOKIE, ""); if (authHeader != null) { String basicCookie = null; try { basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder); if (basicCookie == null) { basicCookie = ""; } } catch (Exception ex) { logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex); basicCookie = ""; } extAuthCookie.setValue(basicCookie); } String authCookieDomain = null; String authCookiePath = null; // Cache cookie properties authCookieDomain = valveConf.getAuthCookieDomain(); authCookiePath = valveConf.getAuthCookiePath(); // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()) .booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { logger.debug("Adding cookie to response"); response.addCookie(extAuthCookie); } //Add cookies to the Cookie array to support sessions authCookies.add(extAuthCookie); logger.debug("Cookie added to the array"); } // Clear webProcessor cookies webProcessor.clearCookies(); } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Garbagge collect method = null; // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP Basic Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:org.openmhealth.reference.servlet.Version1.java
/** * Creates an authentication request, authenticates the user and, if * successful, returns the user's credentials. * //w w w .j av a 2s . c o m * @param username * The username of the user attempting to authenticate. * * @param password * The password of the user attempting to authenticate. * * @param request * The HTTP request object. * * @param response * The HTTP response object. * * @return The authorization token. * * @throws OmhException * There was a problem with the request. This could be any of the * sub-classes of {@link OmhException}. */ @RequestMapping(value = "auth", method = RequestMethod.POST) public @ResponseBody String getAuthentication( @RequestParam(value = PARAM_AUTHENTICATION_USERNAME, required = true) final String username, @RequestParam(value = PARAM_AUTHENTICATION_PASSWORD, required = true) final String password, final HttpServletRequest request, final HttpServletResponse response) throws OmhException { // Create the authentication request from parameters. AuthenticationToken token = handleRequest(request, response, new AuthenticationRequest(username, password)); // Add a cookie for the authentication token. Cookie cookie = new Cookie(PARAM_AUTHENTICATION_AUTH_TOKEN, token.getToken()); // Set the expiration on the cookie. cookie.setMaxAge(new Long((token.getExpires() - System.currentTimeMillis()) / 1000).intValue()); // Build the path without the "auth" part. String requestUri = request.getRequestURI(); cookie.setPath(requestUri.substring(0, requestUri.length() - 5)); // Make sure the cookie is only used with HTTPS. cookie.setSecure(true); // Add the cookie to the response. response.addCookie(cookie); // Return the token. return token.getToken(); }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
@RequestMapping(value = "/logout/**", method = RequestMethod.GET) public ModelAndView logoutPage(HttpServletRequest request, HttpServletResponse response) { // clear cookies/*from w w w. j ava 2s .c o m*/ Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { String ckName = cookies[i].getName(); if (ckName.equals(loginCookie) || ckName.startsWith("_shib")) { log.debug("cookie to clear " + ckName); Cookie c = new Cookie(ckName, "void"); c.setSecure(true); c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } } } /** try { log.debug("redirect to: " + logoutUrl); response.sendRedirect(logoutUrl); } catch (IOException e) { log.error("redirect: " + e); } return emptyMV("configuration error"); **/ String view = "browser"; Device currentDevice = DeviceUtils.getCurrentDevice(request); if (currentDevice != null && currentDevice.isMobile()) view = "mobile"; ModelAndView mv = new ModelAndView(view + "/chooser"); mv.addObject("root", browserRootPath); mv.addObject("vers", request.getServletPath()); mv.addObject("pagetype", "browser/loggedout"); mv.addObject("pathextra", ""); mv.addObject("uwloginpath", standardLoginPath); mv.addObject("googleloginpath", googleLoginPath); mv.addObject("incommonloginpath", incommonLoginPath); return (mv); }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private void sendToLogin(HttpServletRequest request, HttpServletResponse response, String loginPath) { // delete any existing sessions first Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().startsWith("_shib")) { log.debug("clearing cookie " + cookies[i].getName()); Cookie c = new Cookie(cookies[i].getName(), ""); c.setSecure(true);// www . j a v a 2s. c om c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } } } String rp = ""; if (request.getPathInfo() != null) rp = request.getPathInfo(); String rqs = ""; if (request.getQueryString() != null) rqs = "?" + request.getQueryString(); String red = browserRootPath + request.getServletPath() + loginPath + rp + rqs; log.debug("no user yet: redirect for login to " + red); try { response.sendRedirect(red); } catch (IOException e) { log.error("redirect: " + e); } }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response, int method) { String remoteUser = request.getRemoteUser(); if (remoteUser == null && method == 0) { // social login String idp = (String) request.getAttribute("Shib-Identity-Provider"); String mail = (String) request.getAttribute("mail"); log.info("social login from " + idp + ", email = " + mail); if (idp.equals(googleIdentityProvider)) { remoteUser = mail;/*from w ww. j a v a 2 s . c om*/ } else { log.debug("invalid social login"); return emptyMV("invalid social login"); } } String methodKey = "P"; if (method == 2) methodKey = "2"; String aclass = (String) request.getAttribute("Shib-AuthnContext-Class"); if (aclass != null && aclass.equals(SECURE_LOGIN_CLASS)) methodKey = "2"; log.debug("method = " + method + ", key = " + methodKey); if (remoteUser != null) { if (remoteUser.endsWith("@washington.edu")) { remoteUser = remoteUser.substring(0, remoteUser.lastIndexOf("@washington.edu")); log.info("dropped @washington.edu to get id = " + remoteUser); } if (remoteUser.endsWith("@uw.edu")) { // no longer allow google's @uw to be same as UW login // remoteUser = remoteUser.substring(0, remoteUser.lastIndexOf("@uw.edu")); // log.info("dropped @uw.edu to get id = " + remoteUser); ////return loginChooserMV(session, request, response); // return to login chooser // until we can report some misuse return emptyMV("invalid social login"); } double dbl = Math.random(); long modtime = new Date().getTime(); // milliseconds log.debug("login: ck = ...;" + remoteUser + ";" + dbl + ";" + methodKey + ";" + modtime / 1000); String enc = RPCrypt.encode(Double.toString(modtime) + ";" + remoteUser + ";" + dbl + ";" + methodKey + ";" + modtime / 1000); log.debug("login: enc = " + enc); Cookie c = new Cookie(loginCookie, enc); c.setSecure(true); c.setPath("/"); response.addCookie(c); try { String rp = request.getPathInfo(); int sp = rp.indexOf("/", 2); log.debug("in path = " + rp); String red = browserRootPath + request.getServletPath(); if (sp > 1) red = red + rp.substring(sp); if (request.getQueryString() != null) red = red + "?" + request.getQueryString(); log.debug("logon ok, return to " + red); response.sendRedirect(red); } catch (IOException e) { log.error("redirect: " + e); return emptyMV("redirect error"); } } else { // send login failed message ModelAndView mv = new ModelAndView("browser/nologin"); mv.addObject("root", browserRootPath); mv.addObject("vers", request.getServletPath()); mv.addObject("pageTitle", "login failed"); mv.addObject("myEntityId", myEntityId); return mv; } return emptyMV(); }
From source file:com.google.gsa.Kerberos.java
/** * Creates the referer cookie//from w w w . ja v a 2 s. c om * */ private void createRefererCookie(Cookie gsaRefererCookie) { // Instantiate authentication cookie with default value gsaRefererCookie = new Cookie(refererCookieName, valveConf.getTestFormsCrawlUrl()); // Set cookie domain gsaRefererCookie.setDomain(authCookieDomain); // Set cookie path gsaRefererCookie.setPath(authCookiePath); // Set expiration time gsaRefererCookie.setMaxAge(authMaxAge); }
From source file:com.kodemore.servlet.ScServletData.java
public void setCookie(String key, String value, Integer expireSeconds, boolean secure) { value = Kmu.encodeUtf8(value);//from ww w. j a v a2 s . c o m Cookie cookie = new Cookie(key, value); if (expireSeconds != null) cookie.setMaxAge(expireSeconds); if (secure) cookie.setSecure(true); // share cookies across the domain, regardless of the [servlet] path. cookie.setPath("/"); _setCookie(cookie); }