@Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; String cookieName = parameter.getAnnotation(CookieParam.class).value(); Cookie cookie = requestContext.getCookies().get(cookieName); if (cookie == null) { return null; } else { if (Cookie.class.isAssignableFrom(parameter.getType())) { returnValue = cookie; } else if (String.class.isAssignableFrom(parameter.getType())) { returnValue = cookie.getValue(); } else { try { returnValue = objectMapper.readValue(cookie.getValue(), parameter.getType()); } catch (IOException e) { throw new IllegalStateException(e); } } } return returnValue; }
public <I> void putResource(String resourcePath, final I input, Cookie cookie) throws Exception { Response response = null; try { final Invocation.Builder requestBuilder = getRequestBuilder(resourcePath); response = requestBuilder.async().put(Entity.entity(input, this.mediaType), new InvocationLogCallback()) .get(REQUEST_THREAD_TIMEOUT, TimeUnit.MILLISECONDS); Response.Status status = Response.Status.fromStatusCode(response.getStatus()); if (status == Response.Status.OK || status == Response.Status.NO_CONTENT) { this.lastRequestHeaders = response.getHeaders(); } else { throw new ClientResponseNotOkException(); } } catch (Exception ex) { RestClientException restClientException = createRestClientException("PUT", this.webTarget.getUri() + "/" + resourcePath, input, response, ex); log.debug("Error invoking putResource", restClientException); throw restClientException; } }
@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); }
@Override public Response apply(ContainerRequestContext arg0) { SwaggerSpecFilter filter = FilterFactory.getFilter(); if (filter != null) { Map<String, Cookie> cookiesvalue = arg0.getCookies(); Map<String, String> cookies = new HashMap<>(); if (cookiesvalue != null) { for (String key : cookiesvalue.keySet()) { cookies.put(key, cookiesvalue.get(key).getValue()); } } MultivaluedMap<String, String> headers = arg0.getHeaders(); return Response.ok().entity(new VendorSpecFilter().filter(getSwagger(), filter, null, cookies, headers)).build(); } return Response.ok().entity(getSwagger()).build(); }
/** * Prueba para consultar un Client * * @generated */ @Test public void getClientByIdTest() { Cookie cookieSessionId = login(username, password); ClientDTO clientTest = target .path(oraculo.get(0).getId().toString()) .request().cookie(cookieSessionId).get(ClientDTO.class); Assert.assertEquals(clientTest.getId(), oraculo.get(0).getId()); Assert.assertEquals(clientTest.getName(), oraculo.get(0).getName()); Assert.assertEquals(clientTest.getMiddleName(), oraculo.get(0).getMiddleName()); Assert.assertEquals(clientTest.getLastName(), oraculo.get(0).getLastName()); Assert.assertEquals(clientTest.getEmail(), oraculo.get(0).getEmail()); Assert.assertEquals(clientTest.getPhoneNumber(), oraculo.get(0).getPhoneNumber()); Assert.assertEquals(clientTest.getAddress(), oraculo.get(0).getAddress()); Assert.assertEquals(clientTest.getPhoto(), oraculo.get(0).getPhoto()); }
/** * Prueba para consultar un PaymentMethod * * @generated */ @Test public void getPaymentMethodByIdTest() { Cookie cookieSessionId = login(username, password); PaymentMethodDTO paymentMethodTest = target .path(ORACULO.get(0).getId().toString()) .request().cookie(cookieSessionId).get(PaymentMethodDTO.class); Assert.assertEquals(paymentMethodTest.getId(), ORACULO.get(0).getId()); Assert.assertEquals(paymentMethodTest.getName(), ORACULO.get(0).getName()); Assert.assertEquals(paymentMethodTest.getCardType(), ORACULO.get(0).getCardType()); Assert.assertEquals(paymentMethodTest.getCardNumber(), ORACULO.get(0).getCardNumber()); Assert.assertEquals(paymentMethodTest.getSecurityCode(), ORACULO.get(0).getSecurityCode()); Assert.assertEquals(paymentMethodTest.getExpirationMonth(), ORACULO.get(0).getExpirationMonth()); Assert.assertEquals(paymentMethodTest.getExpirationYear(), ORACULO.get(0).getExpirationYear()); }
/** * Prueba para actualizar un Product * * @generated */ @Test public void updateProductTest() throws IOException { Cookie cookieSessionId = login(username, password); ProductDTO product = new ProductDTO(oraculo.get(0)); ProductDTO productChanged = factory.manufacturePojo(ProductDTO.class); product.setName(productChanged.getName()); product.setPrice(productChanged.getPrice()); Response response = target .path(product.getId().toString()) .request().cookie(cookieSessionId) .put(Entity.entity(product, MediaType.APPLICATION_JSON)); ProductDTO productTest = (ProductDTO) response.readEntity(ProductDTO.class); Assert.assertEquals(Ok, response.getStatus()); Assert.assertEquals(product.getName(), productTest.getName()); Assert.assertEquals(product.getPrice(), productTest.getPrice()); }
/** * Prueba para actualizar un Item * * @generated */ @Test public void updateItemTest() throws IOException { Cookie cookieSessionId = login(username, password); ItemDTO item = new ItemDTO(oraculo.get(0)); ItemDTO itemChanged = factory.manufacturePojo(ItemDTO.class); item.setName(itemChanged.getName()); item.setQty(itemChanged.getQty()); Response response = target .path(item.getId().toString()) .request().cookie(cookieSessionId) .put(Entity.entity(item, MediaType.APPLICATION_JSON)); ItemDTO itemTest = (ItemDTO) response.readEntity(ItemDTO.class); Assert.assertEquals(Ok, response.getStatus()); Assert.assertEquals(item.getName(), itemTest.getName()); Assert.assertEquals(item.getQty(), itemTest.getQty()); }
/** * Prueba para actualizar un Category * * @generated */ @Test public void updateCategoryTest() throws IOException { Cookie cookieSessionId = login(username, password); CategoryDTO category = new CategoryDTO(oraculo.get(0)); CategoryDTO categoryChanged = factory.manufacturePojo(CategoryDTO.class); category.setName(categoryChanged.getName()); Response response = target .path(category.getId().toString()) .request().cookie(cookieSessionId) .put(Entity.entity(category, MediaType.APPLICATION_JSON)); CategoryDTO categoryTest = (CategoryDTO) response.readEntity(CategoryDTO.class); Assert.assertEquals(Ok, response.getStatus()); Assert.assertEquals(category.getName(), categoryTest.getName()); }
/** * Prueba para actualizar un Trip * * @generated */ @Test public void updateTripTest() throws IOException { Cookie cookieSessionId = login(username, password); TripDTO trip = new TripDTO(oraculo.get(0)); TripDTO tripChanged = factory.manufacturePojo(TripDTO.class); trip.setName(tripChanged.getName()); trip.setImage(tripChanged.getImage()); trip.setPrice(tripChanged.getPrice()); Response response = target .path(trip.getId().toString()) .request().cookie(cookieSessionId) .put(Entity.entity(trip, MediaType.APPLICATION_JSON)); TripDTO tripTest = (TripDTO) response.readEntity(TripDTO.class); Assert.assertEquals(Ok, response.getStatus()); Assert.assertEquals(trip.getName(), tripTest.getName()); Assert.assertEquals(trip.getImage(), tripTest.getImage()); Assert.assertEquals(trip.getPrice(), tripTest.getPrice()); }
/** * Prueba para actualizar un Agency * * @generated */ @Test public void updateAgencyTest() throws IOException { Cookie cookieSessionId = login(username, password); AgencyDTO agency = new AgencyDTO(oraculo.get(0)); AgencyDTO agencyChanged = factory.manufacturePojo(AgencyDTO.class); agency.setName(agencyChanged.getName()); Response response = target .path(agency.getId().toString()) .request().cookie(cookieSessionId) .put(Entity.entity(agency, MediaType.APPLICATION_JSON)); AgencyDTO agencyTest = (AgencyDTO) response.readEntity(AgencyDTO.class); Assert.assertEquals(Ok, response.getStatus()); Assert.assertEquals(agency.getName(), agencyTest.getName()); }
/** * Login para poder consultar los diferentes servicios * * @param username Nombre de usuario * @param password Clave del usuario * @return Cookie con información de la sesión del usuario * @generated */ public Cookie login(String username, String password) { UserDTO user = new UserDTO(); user.setUserName(username); user.setPassword(password); user.setRememberMe(true); Response response = createWebTarget() .path("users") .path("login") .request() .post(Entity.entity(user, MediaType.APPLICATION_JSON)); if (response.getStatus() == Ok) { return response.getCookies().get(JWT.cookieName); } else { return null; } }
@Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; String cookieName = parameter.getAnnotation(CookieParam.class).value(); Cookie cookie = requestContext.getCookies().get(cookieName); if (cookie == null) { return null; } else { if (Cookie.class.isAssignableFrom(parameter.getType())) { returnValue = cookie; } else if (String.class.isAssignableFrom(parameter.getType())) { returnValue = cookie.getValue(); } else { try { returnValue = objectMapper.readValue(cookie.getValue(), parameter.getType()); } catch (IOException e) { throw new RuntimeException(e); } } } return returnValue; }
/** * Perform logout for the given token. * * @param token - authentication token * @param tokenAccessCookie - old session-based cookie with token. */ public Response logout(String token, Cookie tokenAccessCookie, UriInfo uriInfo) { Response.ResponseBuilder response; String accessToken = token; if (accessToken == null && tokenAccessCookie != null) { accessToken = tokenAccessCookie.getValue(); } boolean secure = uriInfo.getRequestUri().getScheme().equals("https"); if (accessToken != null) { response = Response.ok(); AccessTicket accessTicket = ticketManager.removeTicket(accessToken); if (accessTicket != null) { LOG.info("EVENT#user-sso-logged-out# USER#{}#", accessTicket.getUserId()); } else { LOG.warn("AccessTicket not found. Nothing to do."); } } else { response = Response.status(Response.Status.BAD_REQUEST); LOG.warn("Token not found in request."); } if (cookieBuilder != null) { cookieBuilder.clearCookies(response, accessToken, secure); } return response.build(); }
/** * 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(); }
/** * If the user has a valid session token, set a new session token. The new one should have a later * expiration time. */ @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { String sessionCookieName = sessionCookieConfig.getName(); // If the response will be setting a session cookie, don't overwrite it; just let it go. if (response.getCookies().containsKey(sessionCookieName)) { return; } // If the request doesn't have a session cookie, we're not going to renew one. if (!request.getCookies().containsKey(sessionCookieName)) { return; } Cookie requestCookie = request.getCookies().get(sessionCookieName); Optional<User> optionalUser = authenticator.authenticate(requestCookie); if (optionalUser.isPresent()) { sessionLoginResource.cookiesForUser(optionalUser.get()) .forEach(c -> response.getHeaders().add(HttpHeaders.SET_COOKIE, c)); } }
/** * Creates a request object that is passed to further REST actions. * * @param path The URI that is called. * @param requestHeaders The HTTP headers of the request. * @param requestCookies The cookies of the request. * * @return The request object. */ private Invocation.Builder getRequestObject(String path, Map<String, String> requestHeaders, Set<Cookie> requestCookies) { final String[] splitPath = path.split("\\?"); WebTarget tmpTarget = target.path(splitPath[0]); if (splitPath.length > 1) { for (final String queryParam : splitPath[1].split("&")) { final String[] queryParamPair = queryParam.split("\\="); if (queryParamPair.length == 2) { tmpTarget = tmpTarget.queryParam(queryParamPair[0], queryParamPair[1]); } } } final Invocation.Builder builder = tmpTarget.request(); requestHeaders.forEach(builder::header); requestCookies.forEach(builder::cookie); return builder; }
@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)); } } }
@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); }
@Override public Map<String, Cookie> getCookies() { List<String> values = nettyHttpHeaders.getAll(HttpHeaders.COOKIE); if (values == null || values.isEmpty()) { return Collections.emptyMap(); } Map<String, Cookie> cookieMap = new HashMap<>(); for (String value : values) { if (value == null) { continue; } Cookie cookie = Cookie.valueOf(value); cookieMap.put(cookie.getName(), cookie); } return cookieMap; }
@Override public void setMode(String baseId, Mode mode) { // connect final Client client = newClient(); final Cookie authorization = getAuthorization(client); // ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ // urlBase // ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ WebTarget targetSetMode = client.target(url02).path(urlBase.concat("/").concat(baseId)); decorate(targetSetMode); String json = "{ 'intrusion_settings' : { 'active_mode' : '" + mode.name().toLowerCase() + "' }}"; json = json.replace("'", "\""); Response responseSetMode = targetSetMode.request(MediaType.TEXT_PLAIN_TYPE).cookie(authorization).post(Entity.entity(json, MediaType.TEXT_PLAIN_TYPE)); report(responseSetMode); String entitySetMode = responseSetMode.readEntity(String.class); System.out.println("--> " + entitySetMode); }
public Request( String uri, Object entity, String mediaType, List<Cookie> cookies, Map<String, Object> headers) { _uri = uri; _entity = entity; _mediaType = mediaType; if (cookies != null) { _cookies = cookies; } if (headers != null) { _headers = headers; } }
private Builder prepareRequest(Request request) { WebTarget webTarget = _client.target(request.getUri()); Map<String, String> queryParams = request.getQueryParams(); if (queryParams != null) { for (Entry<String, String> param : queryParams.entrySet()) { webTarget = webTarget.queryParam(param.getKey(), param.getValue()); } } Map<String, Object> pathTemplateParams = request.getPathTemplateParams(); if (pathTemplateParams != null) { webTarget = webTarget.resolveTemplates(pathTemplateParams); } Builder builder = webTarget.request(); for (Cookie currCookie : request.getCookies()) { builder = builder.cookie(currCookie); } for (Entry<String, Object> currEntry : request.getHeaders().entrySet()) { builder = builder.header(currEntry.getKey(), currEntry.getValue()); } return builder; }
public static void startServices() throws Exception { //System.setProperty("bdb.log.level", "trace"); startAdminServer(); ctx = startCacheServer("0"); //URI baseURI = new URI("https://localhost:3443"); URI baseURI = new URI("http://localhost:3030"); ClientConfig clientConfig = new ClientConfig(); Client client = ClientBuilder.newClient(clientConfig); target = client.target(baseURI); LoginParams params = new LoginParams("default", "guest", "password"); Response response = target.path("access/login").request() .header("Content-Type", "application/json") .post(Entity.json(params), Response.class); assertEquals(Status.OK.getStatusCode(), response.getStatus()); Cookie cc = response.getCookies().get(bg_cookie); assertNotNull(cc); assertEquals(bg_cookie, cc.getName()); cuid = cc.getValue(); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final SecurityContext securityContext = requestContext.getSecurityContext(); if (securityContext != null) { logger.debug("filter; auth scheme: {}; secure: {}", securityContext.getAuthenticationScheme(), securityContext.isSecure()); String path = requestContext.getUriInfo().getPath(); if ("access/login".equals(path)) { // just check https if (!securityContext.isSecure()) { requestContext.abortWith(Response.status(Status.NOT_ACCEPTABLE) .entity("Wrong protocol used.").build()); } } else if ("application.wadl".equals(path) || "swagger.json".equals(path) || "swagger.yaml".equals(path)) { return; } else { Cookie cc = requestContext.getCookies().get(bg_cookie); if (cc == null || !checkAuth(cc.getValue())) { requestContext.abortWith(Response.status(Status.UNAUTHORIZED) .entity("No authorization token provided.").build()); } } } else { requestContext.abortWith(Response.status(Status.UNAUTHORIZED) .entity("No security context provided.").build()); } }
@Test public void testLogout() throws Exception { // Response response = target("access/logout").request() .post(null, Response.class); assertEquals(401, response.getStatus()); response = target("access/logout").request() .cookie(bg_cookie, "client-id") .post(null, Response.class); assertEquals(200, response.getStatus()); //assertNull(response.getCookies().get(bg_cookie)); Cookie cc = response.getCookies().get(bg_cookie); assertNotNull(cc); assertEquals(bg_cookie, cc.getName()); assertTrue(cc.toString().endsWith("Max-Age=0")); }
/** * <p>newDeletedCookie.</p> * * @param name a {@link java.lang.String} object. * @return a {@link javax.ws.rs.core.NewCookie} object. */ public static NewCookie newDeletedCookie(String name) { /** * Create a new instance. * * @param name the name of the cookie * @param value the value of the cookie * @param path the URI path for which the cookie is valid * @param domain the host domain for which the cookie is valid * @param version the version of the specification to which the cookie complies * @param comment the comment * @param maxAge the maximum age of the cookie in seconds * @param expiry the cookie expiry date. * @param secure specifies whether the cookie will only be sent over a secure connection * @param httpOnly if {@code true} make the cookie HTTP only, i.e. only visible as part of an HTTP request. * @throws IllegalArgumentException if name is {@code null}. * @since 2.0 */ return new NewCookie(name, DELETED_COOKIE_VALUE, "/", null, Cookie.DEFAULT_VERSION, null, 0, null, false, true); }
/** * <p>newHttpOnlyCookie.</p> * * @param name a {@link java.lang.String} object. * @param value a {@link java.lang.String} object. * @return a {@link javax.ws.rs.core.NewCookie} object. */ public static NewCookie newHttpOnlyCookie(String name, String value) { /** * Create a new instance. * * @param name the name of the cookie * @param value the value of the cookie * @param path the URI path for which the cookie is valid * @param domain the host domain for which the cookie is valid * @param version the version of the specification to which the cookie complies * @param comment the comment * @param maxAge the maximum age of the cookie in seconds * @param expiry the cookie expiry date. * @param secure specifies whether the cookie will only be sent over a secure connection * @param httpOnly if {@code true} make the cookie HTTP only, i.e. only visible as part of an HTTP request. * @throws IllegalArgumentException if name is {@code null}. * @since 2.0 */ return new NewCookie(name, value, null, null, Cookie.DEFAULT_VERSION, null, -1, null, false, true); }
/** * <p>newHttpOnlyCookie.</p> * * @param name a {@link java.lang.String} object. * @param value a {@link java.lang.String} object. * @param maxAge a int. * @return a {@link javax.ws.rs.core.NewCookie} object. */ public static NewCookie newHttpOnlyCookie(String name, String value, int maxAge) { /** * Create a new instance. * * @param name the name of the cookie * @param value the value of the cookie * @param path the URI path for which the cookie is valid * @param domain the host domain for which the cookie is valid * @param version the version of the specification to which the cookie complies * @param comment the comment * @param maxAge the maximum age of the cookie in seconds * @param expiry the cookie expiry date. * @param secure specifies whether the cookie will only be sent over a secure connection * @param httpOnly if {@code true} make the cookie HTTP only, i.e. only visible as part of an HTTP request. * @throws IllegalArgumentException if name is {@code null}. * @since 2.0 */ return new NewCookie(name, value, null, null, Cookie.DEFAULT_VERSION, null, maxAge, null, false, true); }
@Override public T getValue(HttpContext httpContext) { final Cookie cookie = httpContext.getRequest().getCookies().get(this.cookie); if (cookie != null) { final String value = cookie.getValue(); try { final Optional<T> result = authenticator.authenticate(value); if (result.isPresent()) { return result.get(); } } catch (AuthenticationException e) { e.printStackTrace(); } } if (required) { throw new WebApplicationException( Response.status(Response.Status.UNAUTHORIZED) .entity("Credentials are required to access this resource") .type(MediaType.TEXT_PLAIN_TYPE) .build()); } return null; }
@Override public void filter(ContainerRequestContext request) throws IOException { Collection<String> expired = SessionCookieFilter.getExpiredSystems(request); sessionConfigurations.forEach((system, config) -> { Subject subject = SubjectContext.getSubject(system); if (config.getCookieName() != null && subject.getPrincipal() == null) { Cookie cookie = request.getCookies().get(config.getCookieName()); if (cookie != null) { LOGGER.trace("enter() {} - {}", subject, request.getUriInfo().getRequestUri()); HttpCookieToken token = new HttpCookieToken(system, cookie); try { SubjectContext.login(token); } catch (LoginException e) { LOGGER.trace("login failed: {}: {}", e.getClass().getSimpleName(), e.getMessage()); expired.add(system); } } } }); }
public API(String url, String proxyUser, String proxyPassword, URL proxyUrl, int proxyPort, String userAgent, Map<String, Cookie> cookies, boolean isDevel) { config = new ConfigHelper(url, proxyUser, proxyPassword, proxyUrl, proxyPort, userAgent, cookies, isDevel); connectionManager = new ConnectionManager(config); search = new Search(connectionManager); solutions = new Solutions(connectionManager); articles = new Articles(connectionManager); cases = new Cases(connectionManager); products = new Products(connectionManager); comments = new Comments(connectionManager); entitlements = new Entitlements(connectionManager); problems = new Problems(connectionManager); attachments = new Attachments(connectionManager); ping = new Ping(connectionManager); groups = new Groups(connectionManager); symptoms = new Symptoms(connectionManager); insights = new Insights(connectionManager); }
@Override protected byte[] getRememberedSerializedIdentity(SubjectContext subjectContext) { if (isIdentityRemoved()) { return null; } Cookie cookie = Requests.getCookies().get(getCookie().getName()); //no cookie set - new site visitor? if (cookie == null) return null; String base64 = cookie.getValue(); if (Cookies.DELETED_COOKIE_VALUE.equals(base64)) return null; if (base64 != null) { base64 = ensurePadding(base64); logger.trace("Acquired Base64 encoded identity [" + base64 + "]"); byte[] decoded = Base64.decode(base64); logger.trace("Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes."); return decoded; } else { //no cookie set - new site visitor? return null; } }
private Credentials getCredentials(ContainerRequestContext requestContext) throws Exception { Credentials credentials = new Credentials(); Map<String, Cookie> cookies = requestContext.getCookies(); if (cookies != null && cookies.containsKey(AuthResource.AUTH_TOKEN_NAME)) { String rawCookie = cookies.get(AuthResource.AUTH_TOKEN_NAME).getValue(); if (rawCookie.isEmpty()) { LOG.error("Empty cookie. Skipping."); return credentials; } AuthCookie cookie = this.serializer.deserializeCookie(rawCookie); credentials.setPrincipal(cookie.getPrincipal()); credentials.setPassword(cookie.getPassword()); // TODO replace with token in DB } return credentials; }
/** * @param request * @param create * @return */ protected Session getSession(ContainerRequestContext request, boolean create) { Session session = (Session) request.getProperty(SESSION); if (session != null) { return session; } Cookie sessionCookie = request.getCookies().get(AUTH_COOKIE); if (sessionCookie != null) { session = configuration.getSessionStore().getSession(sessionCookie.getValue()); } if (session != null && session.hasExpired(configuration.getSessionExpiryTimeInSecs())) { session = null; } if (session == null && create) { String sessionId = null; if (Strings.isNullOrEmpty(sessionId)) { sessionId = UUID.randomUUID().toString(); } session = configuration.getSessionStore().createSession(sessionId); } return session; }