List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:com.mhe.mediabanksearch.controller.LoginController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { //TO HANDLE: Scenario 1. User comes directly on login page first time. // Scenario 2. User comes on login page but already logged in any other McGraw-Hill's application // Scenario 3. User fill up the login details and click on submit. //TODO: 1. Check for already logged-in user or ERIGHTS cookie // 2. If not already logged in then check if user has tries to login // 3. If user has not tried to login then send to login screen String thumbnailPath = Configuration.getSystemValue(Constants.IMAGE_THUMBNAIL_URL_PATH); String perPageRecordCount = Configuration.getSystemValue(Constants.ASSET_PER_PAGE_IN_CONNECT); String searchManagerName = Configuration.getSystemValue(Constants.SEARCH_MANAGER_NAME); HttpSession session = request.getSession(); session.setAttribute("baseUrl", thumbnailPath); session.setAttribute("perPageRecordCount", perPageRecordCount); session.setAttribute("searchManagerName", searchManagerName); String userAction = null;/* w w w .java 2 s . c om*/ //Implementing Scenario 1. String sessionId = null; String logOutCondition = null; boolean validSession = false; Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { sessionId = getCookieValue(cookies, ERIGHTS, ERIGHTS); logOutCondition = getCookieValue(cookies, LOGOUT, "false"); logOutCondition = logOutCondition.split("~")[0]; if ("true".equalsIgnoreCase(logOutCondition)) { response.addCookie(new Cookie(LOGOUT, "true~refreshed")); return new ModelAndView(LOGIN_VIEW); } if (sessionId != null && !sessionId.equalsIgnoreCase(ERIGHTS)) { validSession = true; validSession = rmsManager.isValidSession(sessionId); } if (validSession) { userAction = "previouslyloggedin"; //userId1 = rmsManager.sessionListUserId(sessionId); } else { userAction = "firsttimelogin"; } } else { userAction = "firsttimelogin"; } //Implementing Scenario 2. long startTime = System.currentTimeMillis(); String userName = request.getParameter(REQ_PARAM_USER_NAME); String password = request.getParameter(REQ_PARAM_PASSWORD); if (userName != null && password != null && session.isNew()) { response.addCookie(new Cookie(LOGOUT, "true")); request.setAttribute("loginErrorMessage", "userError"); return new ModelAndView(LOGIN_VIEW); } boolean inError = false; boolean isServerDown = false; boolean wrongCredentials = false; boolean isSession = true; String role = null; LoginInfo loginInfo = (LoginInfo) session.getAttribute("userData"); if ((userName != null && password != null)) { if (loginInfo == null) { try { loginInfo = rmsManager.loginUser(userName, password); if (!("I".equalsIgnoreCase(loginInfo.getUserType()))) { request.setAttribute("loginErrorMessage", "invalidUser"); return new ModelAndView(LOGIN_VIEW); } isSession = false; } catch (Exception e) { e.printStackTrace(); inError = true; if (e.getCause() != null) { if (e.getCause() instanceof SOAPFaultException) { SOAPFaultException ex = (SOAPFaultException) e.getCause(); String faultString = ex.getFaultString(); String errorCode = faultString.substring(0, faultString.indexOf(":")); if (errorCode.equals(ERROR_CODE_WRONG_CREDENTIALS)) { wrongCredentials = true; } else { isServerDown = true; } } else { isServerDown = true; } } else { isServerDown = true; } } if (isServerDown) { request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_SERVERDOWN); return new ModelAndView(LOGIN_VIEW); } else if (inError) { request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR); return new ModelAndView(LOGIN_VIEW); } else if (wrongCredentials) { request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_WRONG_CREDENTIALS); return new ModelAndView(LOGIN_VIEW); } } if (loginInfo != null) { if (!isSession) { String userId = loginInfo.getUserId(); role = rmsManager.getUserRole(userId); User user = rmsManager.getUserById(userId); String authenticationKey = loginInfo.getSessionId(); session.setAttribute(USER_ID, userId); session.setAttribute(ROLE, role); session.setAttribute(USER_ROLE_DESCRIPTION, AssetUtil.getUserRoleDescription(role)); session.setAttribute(AUTHENTICATION_KEY, authenticationKey); session.setAttribute(USERS_COMPLETE_NAME, user.getFirstName() + SPACE + user.getLastName()); session.setAttribute("userData", loginInfo); response.addCookie(new Cookie("ERIGHTS", authenticationKey)); } else { session.getAttribute(ROLE); } if (_logger.isDebugEnabled()) { long endTime = System.currentTimeMillis(); _logger.debug( "Total execution time for Login Controller is : " + (endTime - startTime) + " ms."); } //http://connectqastaging.mhhe.com/imagebanksearch/home.ibs?courseIsbn=0073273163&providerIsbn=0072859342 //return new ModelAndView(new RedirectView("/imagebanksearch/home.ibs")); //session.setAttribute("providerIsbn", "0073273163"); //session.setAttribute("courseIsbn", "0072859342"); //License lic = rmsManager.getAllLicenseProducts(Integer.parseInt(loginInfo.getUserId())); request.setAttribute("isStandalone", true); response.addCookie(new Cookie(LOGOUT, "false")); return new ModelAndView("initial.view"); } else { request.setAttribute(REQ_ATTR_LOGIN_ERROR_MESSAGE, REQ_ATTR_IN_ERROR); return new ModelAndView(REQ_FRWD_ASSET_VAULT_LOGIN); } } //Implementing Scenario 3. //sending to appropriate view if (userAction != null && "firsttimelogin".equalsIgnoreCase(userAction)) { return new ModelAndView(LOGIN_VIEW); } else if (userAction != null && "previouslyloggedin".equalsIgnoreCase(userAction)) { request.setAttribute("isStandalone", true); return new ModelAndView("initial.view"); } return new ModelAndView(LOGIN_VIEW); }
From source file:com.adobe.acs.commons.wcm.notifications.impl.SystemNotificationsImplTest.java
@Test public void testFilterWhenDismissed() throws Exception { setAuthorRunmode();/*from w w w .j a v a 2 s . c om*/ createEnabledNotification(); aemContext.registerInjectActivateService(notifications); aemContext.request().setResource(aemContext.resourceResolver().getResource("/")); aemContext.request().addCookie(new Cookie("acs-commons-system-notifications", "uid-" + DigestUtils.shaHex("/etc/acs-commons/notifications/enabled0"))); notifications.doFilter(aemContext.request(), aemContext.response(), outputChain); String output = aemContext.response().getOutputAsString(); assertEquals(output.trim(), "<html><body></body></html>"); }
From source file:de.sainth.recipe.backend.security.AuthFilter.java
private Cookie createCookie(RecipeManagerAuthenticationToken authentication, boolean secure) { String newToken = Jwts.builder() // .compressWith(new GzipCompressionCodec()) .setSubject(authentication.getPrincipal().toString()) .setExpiration(/*from w ww . ja va 2s . co m*/ Date.from(LocalDateTime.now().plusMinutes(30).atZone(ZoneId.systemDefault()).toInstant())) .claim(TOKEN_ROLE, authentication.getAuthorities().get(0).getAuthority()).setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, key).compact(); Cookie cookie = new Cookie(COOKIE_NAME, newToken); cookie.setSecure(secure); cookie.setHttpOnly(true); cookie.setMaxAge(30 * 60); return cookie; }
From source file:org.kievguide.controller.UserController.java
@RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logOut(HttpServletResponse response) { ModelAndView modelAndView = new ModelAndView(); Cookie logOutCookie = new Cookie("userstatus", "guest"); String userStatus = Util.guestPanel(); modelAndView.addObject("userstatus", userStatus); response.addCookie(logOutCookie);/*from ww w . j av a 2 s. c om*/ modelAndView.setViewName("redirect:" + "signinredirect"); return modelAndView; }
From source file:org.gatein.sso.agent.opensso.OpenSSOAgentImpl.java
/** * This method is useful only for Cross-Domain (CD) authentication scenario when GateIn and OpenSSO are in different DNS domains and they can't share cookie. * * It performs://from w w w . j av a2 s.c o m * <li>Parse and validate message from OpenSSO CDCServlet.</li> * <li>Use ssoToken from parsed message and establish OpenSSO cookie iPlanetDirectoryPro</li> * <li>Redirects to InitiateLoginFilter but with cookie established. So in next request, we can perform agent validation against OpenSSO server</li> * * @param httpRequest * @param httpResponse * @return true if parameter LARES with message from CDC is present in HttpServletRequest * @throws IOException */ protected boolean tryMessageFromCDC(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { String encodedCDCMessage = httpRequest.getParameter("LARES"); if (encodedCDCMessage == null) { if (log.isTraceEnabled()) { log.trace("Message from CDC not found in this HttpServletRequest"); } return false; } CDMessageContext messageContext = cdcMessageParser.parseMessage(encodedCDCMessage); if (log.isTraceEnabled()) { log.trace("Successfully parsed messageContext " + messageContext); } // Validate received messageContext validateCDMessageContext(httpRequest, messageContext); // Establish cookie with ssoToken String ssoToken = messageContext.getSsoToken(); Cookie cookie = new Cookie(cookieName, "\"" + ssoToken + "\""); cookie.setPath(httpRequest.getContextPath()); httpResponse.addCookie(cookie); if (log.isTraceEnabled()) { log.trace("Cookie " + cookieName + " with value " + ssoToken + " added to HttpResponse"); } // Redirect again this request to be processed by OpenSSOAgent. Now we have cookie established String urlToRedirect = httpResponse.encodeRedirectURL(httpRequest.getRequestURI()); httpResponse.sendRedirect(urlToRedirect); return true; }
From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java
void saveUserInformationInCookie(String username, String firstName, String lastName, String email, OAuth2AccessToken accessToken, HttpServletResponse response) throws UnsupportedEncodingException { try {/*ww w. j ava 2 s . c o m*/ Cookie cookie = new Cookie(Categolj2Cookies.USER_COOKIE, objectMapper.writeValueAsString(new UserInfo(username, firstName, lastName, email))); cookie.setMaxAge(getRefreshTokenMaxAge(accessToken)); response.addCookie(cookie); } catch (JsonProcessingException e) { logger.error("JSON conversion failed!", e); } }
From source file:de.theit.jenkins.crowd.CrowdServletFilter.java
/** * {@inheritDoc}/* w ww .jav a2 s . com*/ * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // check if we have a token // if it is not present, we are not / no longer authenticated boolean isValidated = false; try { isValidated = this.configuration.crowdHttpAuthenticator.isAuthenticated(req, res); } catch (OperationFailedException ex) { LOG.log(Level.SEVERE, operationFailed(), ex); } if (!isValidated) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("User is not logged in (anymore) via Crowd => logout user"); } SecurityContext sc = SecurityContextHolder.getContext(); sc.setAuthentication(null); // close the SSO session if (null != this.rememberMe) { this.rememberMe.logout(req, res); } // invalidate the current session // (see SecurityRealm#doLogout()) HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); } SecurityContextHolder.clearContext(); // reset remember-me cookie Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, ""); cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/"); res.addCookie(cookie); } else { SecurityContext sc = SecurityContextHolder.getContext(); if (!(sc.getAuthentication() instanceof CrowdAuthenticationToken)) { // user logged in via Crowd, but no Crowd-specific // authentication token available // => try to auto-login the user if (null != this.rememberMe) { if (LOG.isLoggable(Level.FINE)) { LOG.fine( "User is logged in via Crowd, but no authentication token available; trying auto-login..."); } Authentication auth = this.rememberMe.autoLogin(req, res); if (null != auth) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("User sucessfully logged in"); } sc.setAuthentication(auth); } } } } } this.defaultFilter.doFilter(request, response, chain); }
From source file:com.kingcore.framework.util.CookieUtils.java
/** * domain clearCookie//from w w w. j a v a2 s . c om * The form of the domain name is specified by RFC 2109. A domain name begins with a dot (.foo.com) * and means that the cookie is visible to servers in a specified Domain Name System (DNS) zone * (for example, www.foo.com, but not a.b.foo.com). By default, cookies are only returned to * the server that sent them. * @param name ?Cookie?? * @param response ? * @param domain Cookie?? */ public static void clearCookie(String name, HttpServletResponse response, String domain) { Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); cookie.setPath("/"); cookie.setDomain(domain); response.addCookie(cookie); }
From source file:com.google.identitytoolkit.GitkitClientTest.java
public void testGetOobCode() throws Exception { Cookie[] gitkitCookie = { new Cookie("gtoken", "fake-token") }; HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); when(mockRequest.getCookies()).thenReturn(gitkitCookie); when(mockRequest.getParameter("action")).thenReturn("resetPassword"); when(mockRequest.getParameter("email")).thenReturn("1111@example.com"); when(mockRequest.getParameter("challenge")).thenReturn("what is the number"); when(mockRequest.getParameter("response")).thenReturn("8888"); when(mockRequest.getRemoteUser()).thenReturn("1.1.1.1"); String expectedApiUrl = GitkitClient.GITKIT_API_BASE + "getOobConfirmationCode"; when(mockSender.post(eq(expectedApiUrl), anyString(), eq(headers))) .thenReturn("{'oobCode':'fake-oob-code'}"); GitkitClient.OobResponse oobResponse = gitkitClient.getOobResponse(mockRequest); assertEquals(GitkitClient.OobAction.RESET_PASSWORD, oobResponse.getOobAction()); assertEquals("http://example.com:80/gitkit?mode=resetPassword&oobCode=fake-oob-code", oobResponse.getOobUrl().get()); }
From source file:com.mockey.model.ResponseFromService.java
private void setCookiesFromHeader(Header[] headers) { for (Header header : headers) { if (header.getName().equals("Set-Cookie")) { String headerValue = header.getValue(); // Parse cookie String[] fields = headerValue.split(";\\s*"); //String cookieValue = fields[0]; //String expires = null; String path = null;//from w w w . j a v a2 s.c o m String domain = null; boolean secure = false; // Parse each field for (int j = 1; j < fields.length; j++) { if ("secure".equalsIgnoreCase(fields[j])) { secure = true; } else if (fields[j].indexOf('=') > 0) { String[] f = fields[j].split("="); if ("expires".equalsIgnoreCase(f[0])) { //expires = f[1]; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } String[] cookieParts = headerValue.split("=", 2); String cookieBody = cookieParts[1]; String[] cookieBodyParts = cookieBody.split("; "); Cookie cookie = new Cookie(cookieParts[0], cookieBodyParts[0]); cookie.setDomain(domain); cookie.setPath(path); cookie.setSecure(secure); // if(expires!=null){ // Date expiresTime = null; // try { // expiresTime = HttpCookieDateUtil.parseDate(expires); // Date nowTime = new Date(); // long maxAge = nowTime.getTime() - expiresTime.getTime(); // cookie.setMaxAge((int) maxAge/1000); // }catch(Exception e){ // log.error("Unable to calculate maxAge with expiration date "+expiresTime, e); // } // } this.cookieList.add(cookie); } } }