@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response create(@NotNull @Valid final AcquisitionRequest request, @Context final HttpServletRequest httpRequest) { final AcquisitionFlow acquisitionFlow = credentials.acquire(connectorId, apiBase(httpRequest), absoluteTo(httpRequest, request.getReturnUrl())); final CredentialFlowState flowState = acquisitionFlow.state().get(); final NewCookie cookie = state.persist(flowState.persistenceKey(), "/", flowState); final AcquisitionResponse acquisitionResponse = AcquisitionResponse.Builder.from(acquisitionFlow) .state(State.Builder.cookie(cookie.toString())).build(); return Response.accepted().entity(acquisitionResponse).build(); }
@Test public void shouldPersistAsInRfcErrata() { final ClientSideState clientSideState = new ClientSideState(RFC_EDITION, RFC_TIME, RFC_IV_SOURCE, SIMPLE_SERIALIZATION, SIMPLE_DESERIALIZATION, ClientSideState.DEFAULT_TIMEOUT); final NewCookie cookie = clientSideState.persist("id", "/path", "a state string"); assertThat(cookie).isNotNull(); assertThat(cookie.getName()).isEqualTo("id"); assertThat(cookie.getValue()) .isEqualTo("pzSOjcNui9-HWS_Qk1Pwpg|MTM0NzI2NTk1NQ|dGlk|tL3lJPf2nUSFMN6dtVXJTw|uea1fgC67RmOxfpNz8gMbnPWfDA"); assertThat(cookie.getPath()).isEqualTo("/path"); assertThat(cookie.isHttpOnly()).isFalse(); assertThat(cookie.isSecure()).isTrue(); }
@Test public void shouldRestoreMultipleAndOrderByTimestamp() { final Iterator<Long> times = Arrays .asList(946598400L, 1293753600L, 978220800L, 946598400L, 1293753600L, 978220800L).iterator(); final ClientSideState clientSideState = new ClientSideState(RFC_EDITION, () -> times.next(), ClientSideState.DEFAULT_TIMEOUT); final NewCookie cookie1999 = clientSideState.persist("key", "/path", "1"); final NewCookie cookie2010 = clientSideState.persist("key", "/path", "3"); final NewCookie cookie2000 = clientSideState.persist("key", "/path", "2"); final Set<String> restored = clientSideState.restoreFrom(Arrays.asList(cookie1999, cookie2010, cookie2000), String.class); assertThat(restored).containsExactly("3", "2", "1"); }
/** * Logs in the user with email address and password. * Returns the user on success. * * @param email The user's email address. * @param password The user's plain text password. * @return the user details. */ public NewCookie login(final String email, final String password) { final SecurityUser candidate = dao.findUserByEmail(userClass, email); if (candidate == null) { throw new BadRequestException("notfound"); } if (candidate.getPasswordHash() == null) { throw new BadRequestException("invalid"); } if (!BCrypt.checkpw(password, candidate.getPasswordHash())) { throw new BadRequestException("incorrect"); } return loginAs(candidate); }
@Test public void testLogout() { final User user = new User(); final UserSession session = new UserSession(); session.setUser(user); final String cookie = session.getId().toString(); final SecurityDao dao = mock(SecurityDao.class); when(dao.read(eq(UserSession.class), eq(session.getId()))).thenReturn(session); when(dao.read(eq(User.class), eq(user.getId()))).thenReturn(user); final Configuration config = mock(Configuration.class); when(config.getProperty(eq(MinijaxProperties.SECURITY_USER_CLASS))).thenReturn(User.class); final Security<User> security = new Security<>(dao, config, null, cookie); final NewCookie newCookie = security.logout(); assertNotNull(newCookie); assertEquals("", newCookie.getValue()); verify(dao).purge(eq(session)); }
@Override public NewCookie fromString(final String value) { if (value == null || value.isEmpty()) { return null; } final List<HttpCookie> httpCookies = HttpCookie.parse(value); final HttpCookie httpCookie = httpCookies.get(0); return new NewCookie( httpCookie.getName(), httpCookie.getValue(), httpCookie.getPath(), httpCookie.getDomain(), httpCookie.getVersion(), httpCookie.getComment(), (int) httpCookie.getMaxAge(), null, httpCookie.getSecure(), httpCookie.isHttpOnly()); }
@Override @SuppressWarnings("unchecked") public <T> HeaderDelegate<T> createHeaderDelegate(final Class<T> type) { if (type == MediaType.class) { return (HeaderDelegate<T>) MEDIA_TYPE_DELEGATE; } if (type == Cookie.class) { return (HeaderDelegate<T>) COOKIE_DELEGATE; } if (type == NewCookie.class) { return (HeaderDelegate<T>) NEW_COOKIE_DELEGATE; } if (type == CacheControl.class) { return (HeaderDelegate<T>) CACHE_CONTROL_DELEGATE; } throw new IllegalArgumentException("Unrecognized header delegate: " + type); }
@POST @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Authenticate a user", notes = "Verify a user credentials") @ApiResponses(value = { @ApiResponse(code = 200, message = "user authenticated"), @ApiResponse(code = 401, message = "Wrong user or password")}) public Response authenticate(Credentials credentials) { if (UsersDao.authenticate(credentials)) { byte[] bearer = UsersDao.getBearer(credentials); StringBuilder auth = new StringBuilder().append("Bearer ").append(PasswordStorage.toBase64(bearer)); return Response.ok() .cookie(new NewCookie("Authorization", auth.toString(), null, null, DEFAULT_VERSION, null, DEFAULT_MAX_AGE, null, true, true)) .entity(new ResponseMessage(true, "user authenticated")).build(); } else { return Response.status(UNAUTHORIZED) .entity(new ResponseMessage(false, "Username or password is incorrect")).build(); } }
@Test public void testGetCookie() throws Exception { NewCookie cookie1 = ParsecHttpUtil.getCookie(new Cookie( "cookie1_name", "cookie1_value", false, null, "cookie1_path", 1, true, true )); assertEquals("cookie1_name", cookie1.getName()); assertEquals("cookie1_value", cookie1.getValue()); assertEquals(null, cookie1.getDomain()); assertEquals("cookie1_path", cookie1.getPath()); assertEquals(null, cookie1.getExpiry()); assertEquals(1, cookie1.getMaxAge()); assertTrue(cookie1.isSecure()); assertTrue(cookie1.isHttpOnly()); }
public void populateResponse(ContainerResponseContext responseContext) { if (hasResponseContent) { responseContext.setEntity(responseContent); } if (hasResponseContentType) { responseContext.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, responseContentType); } if (hasResponseStatus) { responseContext.setStatus(responseStatus); } for (Entry<String, String> headers : responseHeaders.entrySet()) { responseContext.getHeaders().putSingle(headers.getKey(), headers.getValue()); } for (NewCookie cookie : responseCookies) { responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie); } }
/** * Retrieve a stock for a given symbol. * http://localhost:9090/stockquote/IBM * * @param symbol Stock symbol will be taken from the path parameter. * @return Response */ @GET @Path("/{symbol}") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Return stock quote corresponding to the symbol", notes = "Returns HTTP 404 if the symbol is not found") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid stock item found"), @ApiResponse(code = 404, message = "Stock item not found")}) public Response getQuote(@ApiParam(value = "Symbol", required = true) @PathParam("symbol") String symbol) throws SymbolNotFoundException { Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException("Symbol " + symbol + " not found"); } return Response.ok().entity(stock).cookie(new NewCookie("symbol", symbol)).build(); }
@POST @Produces("text/html") public Response createCustomer(@FormParam("firstname") String first, @FormParam("lastname") String last) { Customer customer = new Customer(); customer.setId(idCounter.incrementAndGet()); customer.setFirstName(first); customer.setLastName(last); customerDB.put(customer.getId(), customer); System.out.println("Created customer " + customer.getId()); String output = "Created customer <a href=\"customers/" + customer.getId() + "\">" + customer.getId() + "</a>"; String lastVisit = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date()); URI location = URI.create("/customers/" + customer.getId()); return Response.created(location) .entity(output) .cookie(new NewCookie("last-visit", lastVisit)) .build(); }
@GET @Path("{id}") @Produces("text/plain") public Response getCustomer(@PathParam("id") int id, @HeaderParam("User-Agent") String userAgent, @CookieParam("last-visit") String date) { final Customer customer = customerDB.get(id); if (customer == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } String output = "User-Agent: " + userAgent + "\r\n"; output += "Last visit: " + date + "\r\n\r\n"; output += "Customer: " + customer.getFirstName() + " " + customer.getLastName(); String lastVisit = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date()); return Response.ok(output) .cookie(new NewCookie("last-visit", lastVisit)) .build(); }
@POST @Path("/login") @Produces("application/json") @Consumes("application/json") public Response authenticateUser(Credentials credentials) { boolean authenticated = authenticator.authenticate(credentials); if(authenticated) { Session session = issueToken(credentials.getUsername()); NewCookie cookie = new NewCookie("sessionid", session.getToken(), "/", null, 1, null, -1, null, false, false); Profile profile = getProfile(credentials.getUsername()); session.setProfile(profile); return Response.ok(session).cookie(cookie).build(); } else { return Response.status(Response.Status.UNAUTHORIZED).build(); } }
public void setCookies( Response.ResponseBuilder builder, String token, boolean secure, boolean isAnonymous) { builder.header( "Set-Cookie", new NewCookie( "token-access-key", token, accessCookiePath, null, null, ticketLifeTimeSeconds, secure) + ";HttpOnly"); builder.header( "Set-Cookie", new NewCookie("session-access-key", token, "/", null, null, -1, secure) + ";HttpOnly"); if (!isAnonymous) { builder.cookie( new NewCookie("logged_in", "true", "/", null, null, ticketLifeTimeSeconds, secure)); } }
@GET @Path("/authentication-point/authenticate") public Response login( @HeaderParam(HttpHeaders.AUTHORIZATION) String authorization, @Context UriInfo uriInfo) { if (authorization.contains("Basic")) { NewCookie cookie = new NewCookie("LWSSO_COOKIE_KEY", UUID.randomUUID().toString()); updateCookieHolder(cookie); return Response.ok().cookie(cookie).build(); } else { return unauthorizedResponse(uriInfo); } }
@Test public void testSessions() { testFactory.app("-s") .module(b -> JettyModule.extend(b).addServlet(new TestServlet(), "s1", "/*")) .autoLoadModules() .run(); WebTarget base = ClientBuilder.newClient().target("http://localhost:8080"); Response r1 = base.path("/").request().get(); assertEquals(Status.OK.getStatusCode(), r1.getStatus()); assertEquals("count: 1", r1.readEntity(String.class)); NewCookie sessionId = r1.getCookies().get("JSESSIONID"); assertNotNull(sessionId); Response r2 = base.path("/").request().cookie(sessionId).get(); assertEquals(Status.OK.getStatusCode(), r2.getStatus()); assertEquals("count: 2", r2.readEntity(String.class)); }
@Path("/login") @POST public Response loginUser(@Valid final LoginRequest loginRequest) { final String email = loginRequest.getEmail(); final String password = loginRequest.getPassword(); final Optional<LoginResult> maybeResult = usersService.loginUser(email, password); if (maybeResult.isPresent()) { final LoginResult result = maybeResult.get(); return Response.seeOther( UriBuilder.fromResource(UsersResource.class) .path(UsersResource.class, "getUser") .build(result.getUserId())) .cookie(new NewCookie(jwtConfiguration.getCookieName(), result.getToken())) .build(); } else { throw Exceptions.webAppException(UsersService.USER_NOT_FOUND, Response.Status.NOT_FOUND); } }
/** * Logout and remove any session cookies * * @description Log out and remove any session cookies * @responseMessage 200 Logged out successfully */ @Timed @ExceptionMetered @POST @Produces(APPLICATION_JSON) public Response logout(@Nullable @CookieParam(value = "session") Cookie sessionCookie) { if (sessionCookie != null) { Optional<User> user = cookieAuthenticator.authenticate(sessionCookie); if (user.isPresent()) { logger.info("User logged out: {}", user.get().getName()); } else { logger.warn("Invalid user cookie on logout."); } } NewCookie expiredCookie = cookieFactory.getExpiredSessionCookie(); return Response.ok() .header(HttpHeaders.SET_COOKIE, expiredCookie.toString()) .build(); }
@Test public void sendsExpiredCookie() throws Exception { Request request = new Request.Builder() .post(RequestBody.create(MediaType.parse("text/plain"), "")) .url(testUrl("/admin/logout")) .build(); Response response = client.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); List<String> cookies = response.headers(HttpHeaders.SET_COOKIE); assertThat(cookies).hasSize(1); NewCookie cookie = NewCookie.valueOf(cookies.get(0)); assertThat(cookie.getName()).isEqualTo("session"); assertThat(cookie.getValue()).isEqualTo("expired"); assertThat(cookie.getVersion()).isEqualTo(1); assertThat(cookie.getPath()).isEqualTo("/admin"); assertThat(cookie.isSecure()).isTrue(); assertThat(cookie.isHttpOnly()).isTrue(); assertThat(cookie.getExpiry()).isEqualTo(new Date(0)); }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); for (String name : requestContext.getPropertyNames()) { if (name.startsWith("rb_session")) { Object rbSession = requestContext.getProperty(name); headers.add("Set-Cookie", new NewCookie(name, rbSession.toString(), "/", null, Cookie.DEFAULT_VERSION, null, NewCookie.DEFAULT_MAX_AGE, null, false, false)); } } }
/** * Get a new login cookie * * @param em used to persist cookie * @param user user that logged in * @param client client that has logged in * @return */ public static NewCookie getNewCookie( final EntityManager em, final User user, final Client client ) { final LoginCookie loginCookie = generateLoginCookie(em, user); if (loginCookie == null) { return null; } return new NewCookie( getCookieName(client), loginCookie.getSecret(), "/", null, NewCookie.DEFAULT_VERSION, null, 60 * 60 * 24 * 30, loginCookie.getExpires(), true, true ); }
@GET @Timed @Path(value = "/logout") public Response logout(@Context final HttpServletRequest request) { // invalidate cookie if exists ResponseBuilder reply = Response.ok(); for (Cookie c : request.getCookies()) { if (OAuth2AuthFilter.AUTH_COOKIE_NAME.equals(c.getName())) { reply.cookie(new NewCookie(OAuth2AuthFilter.AUTH_COOKIE_NAME, null, "/", request.getServerName(), null, 0, true)); break; } } return reply.build(); }
@Test public void testFromStringWithExtendedParameters() { String cookieString = "Version=1; Application=msf4j; Path=/carbon; Domain=wso2; Expires=Sun, 06 Nov 1994 " + "08:49:37 GMT; Secure; HttpOnly; MaxAge=50; Comment=TestOnly"; String name = "Application"; String value = "msf4j"; String path = "/carbon"; String domain = "wso2"; long dateTime = 784111777000L; NewCookie cookie = (NewCookie) Cookie.valueOf(cookieString); assertEquals(cookie.getName(), name); assertEquals(cookie.getValue(), value); assertEquals(cookie.getPath(), path); assertEquals(cookie.getVersion(), 1); assertEquals(cookie.getDomain(), domain); assertEquals(cookie.getComment(), "TestOnly"); assertEquals(cookie.getExpiry().getTime(), dateTime); assertEquals(cookie.getMaxAge(), 50); assertEquals(cookie.isSecure(), true); assertEquals(cookie.isHttpOnly(), true); }
/** * Retrieve a stock for a given symbol. * http://localhost:8080/stockquote/IBM * * @param symbol Stock symbol will be taken from the path parameter. * @return Response */ @GET @Path("/{symbol}") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Return stock quote corresponding to the symbol", notes = "Returns HTTP 404 if the symbol is not found") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid stock item found"), @ApiResponse(code = 404, message = "Stock item not found")}) public Response getQuote(@ApiParam(value = "Symbol", required = true) @PathParam("symbol") String symbol) throws SymbolNotFoundException { Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException("Symbol " + symbol + " not found"); } return Response.ok().entity(stock).cookie(new NewCookie("symbol", symbol)).build(); }
/** * Retrieve a stock for a given symbol. * http://localhost:8080/stockquote/IBM * * @param symbol Stock symbol will be taken from the path parameter. * @return Response */ @GET @Path("/{symbol}") @Produces({"application/json", "text/xml"}) @ApiOperation( value = "Return stock quote corresponding to the symbol", notes = "Returns HTTP 404 if the symbol is not found") @ApiResponses(value = { @ApiResponse(code = 200, message = "Valid stock item found"), @ApiResponse(code = 404, message = "Stock item not found")}) public Response getQuote(@ApiParam(value = "Symbol", required = true) @PathParam("symbol") String symbol) throws SymbolNotFoundException { System.out.println("Getting symbol using PathParam..."); Stock stock = stockQuotes.get(symbol); if (stock == null) { throw new SymbolNotFoundException("Symbol " + symbol + " not found"); } return Response.ok().entity(stock).cookie(new NewCookie("symbol", symbol)).build(); }
@Override protected Result check() throws Exception { LOGGER.info("Begin session health check"); // Login: Credentials credentials = new Credentials(sessionHealthCheckHelper.getTechnicalUserName(), sessionHealthCheckHelper.getTechnicalUserPassword(), false); Response loginResponse = sessionHealthCheckHelper.getSessionResource().request().post(Entity.json(credentials)); if (Response.Status.OK.getStatusCode() != loginResponse.getStatus()) { LOGGER.warn("Login request failed: {}", loginResponse.getStatus()); return Result.unhealthy("Login request failed", loginResponse); } NewCookie loginCookie = loginResponse.getCookies().get("sessionToken"); // Check if protected resource is accessible Response sessionLoggedIn = sessionHealthCheckHelper.getSessionResource().request().cookie(loginCookie).get(); if (Response.Status.OK.getStatusCode() != sessionLoggedIn.getStatus()) { LOGGER.warn("User wasn't logged in after successful login response: {}", sessionLoggedIn.getStatus()); return Result.unhealthy("User wasn't logged in after successful login response", sessionLoggedIn); } LOGGER.info("Session health check finished successfully"); return Result.healthy(); }
@NotNull protected NewCookie registerAndLogin(String testUsername, String testPassword) { // Register new user: RegistrationRequestData registrationRequestData = new RegistrationRequestData().setName(testUsername).setPassword(testPassword).setConfirmPassword(testPassword); Response registrationResponse = getTarget().path("/register").request().post(Entity.json(registrationRequestData)); assertEquals("User registration failed - this indicates an error in the authentication subsystem", Response.Status.ACCEPTED.getStatusCode(), registrationResponse.getStatus()); // Login: Credentials credentials = new Credentials(testUsername, testPassword, false); Response loginResponse = getTarget().path("/session").request().post(Entity.json(credentials)); assertEquals("User login failed - this indicates an error in the authentication subsystem", Response.Status.OK.getStatusCode(), loginResponse.getStatus()); NewCookie loginCookie = loginResponse.getCookies().get("sessionToken"); assertTrue("Session cookie may not be empty - this indicates an error in the authentication subsystem", StringUtils.isNotEmpty(loginCookie.getValue())); return loginCookie; }
NewCookie createLoginCookie(HttpServletRequest req, SSOPrincipal principal) { String token = principal.getTokenStr(); // if expires is negative, it means the cookie must be transient int expires = (principal.getExpires() <= -1) ? NewCookie.DEFAULT_MAX_AGE : (int) ((principal.getExpires() - getTimeNow()) / 1000); NewCookie authCookie = new NewCookie( HttpUtils.getLoginCookieName(), token, "/", null, null, expires, (req.isSecure() || secureLoadBalancer) ); return authCookie; }
/** * * @param client * @return */ protected String getJsessionFromServer(Client client) { Options options = new Options(); options.setMonitor(true); MessageFromClient mfc = getMessageFromClient(OcelotServices.class, "initCore", getJson(options)); WebTarget target = client.target("http://localhost:" + PORT + "/" + CTXPATH).path("ocelot").path("endpoint"); Response res = target.request(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON).post(Entity.form(new Form("mfc", mfcToJson(mfc)))); res.readEntity(String.class); res = target.request(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON).post(Entity.form(new Form("mfc", mfcToJson(mfc)))); NewCookie jsession = res.getCookies().get("JSESSIONID"); String result = res.readEntity(String.class); try { MessageToClient mtc = mtcFromJson(result); assertThat(mtc.getType()).isEqualTo(MessageType.RESULT); } catch (Throwable t) { t.printStackTrace(); } return jsession.getValue(); }
@GET @Path("/logout") @Produces("text/plain") public Response logout(@QueryParam("login") String login, @CookieParam("sessionid") String sessionid) { try { // TODO: seems to be a bug with chrome on the sessionid. This has always existed... // Looks like a difference between how the node.js app and java app handle cookies. if (sessionid.equals("")) { System.out.println("sessionid is empty"); } else { authService.invalidateSession(sessionid); } // The following call will trigger query against all partitions, disable for now // customerService.invalidateAllUserSessions(login); // TODO: Want to do this with setMaxAge to zero, but to do that I need to have the same path/domain as cookie // created in login. Unfortunately, until we have a elastic ip and domain name its hard to do that for "localhost". // doing this will set the cookie to the empty string, but the browser will still send the cookie to future requests // and the server will need to detect the value is invalid vs actually forcing the browser to time out the cookie and // not send it to begin with NewCookie sessCookie = new NewCookie(SESSIONID_COOKIE_NAME, ""); return Response.ok("logged out").cookie(sessCookie).build(); } catch (Exception e) { e.printStackTrace(); return null; } }
/** * @return the new cookies retrieved from the response */ @PublicAtsApi public NewCookie[] getNewCookies() { Collection<NewCookie> newCookies = response.getCookies().values(); return newCookies.toArray(new NewCookie[newCookies.size()]); }
@Test(expected = IllegalArgumentException.class) public void shouldComplainAboutStalePickles() { final ClientSideState clientSideStateOld = new ClientSideState(RFC_EDITION, () -> ClientSideState.currentTimestmpUtc() - ClientSideState.DEFAULT_TIMEOUT - 100, ClientSideState.DEFAULT_TIMEOUT); final ClientSideState clientSideStateCurrent = new ClientSideState(RFC_EDITION, () -> ClientSideState.currentTimestmpUtc(), ClientSideState.DEFAULT_TIMEOUT); final NewCookie persisted = clientSideStateOld.persist("key", "/path", "value"); clientSideStateCurrent.restoreFrom(persisted, String.class); }
@Test(expected = IllegalArgumentException.class) public void shouldComplainAboutTidMismatch() { final ClientSideState clientSideState1 = new ClientSideState(RFC_EDITION); final ClientSideState clientSideState2 = new ClientSideState(withCustomTid(new byte[] {2})); final NewCookie persisted = clientSideState1.persist("key", "/path", "value"); clientSideState2.restoreFrom(persisted, String.class); }
@Test public void shouldRoundtripMaps() { final ClientSideState clientSideState = new ClientSideState(RFC_EDITION); final Map<String, String> data = new HashMap<>(); data.put("k1", "v1"); data.put("k2", "v2"); final NewCookie cookie = clientSideState.persist("key", "/path", data); @SuppressWarnings("unchecked") final Map<String, String> value = clientSideState.restoreFrom(cookie, Map.class); assertThat(value).isEqualTo(data); }