javax.ws.rs.core.Cookie Java Examples

The following examples show how to use javax.ws.rs.core.Cookie. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Request.java    From verigreen with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #2
Source File: CookieRenewingFilter.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
  }
}
 
Example #3
Source File: FirebaseAuthSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/profile")
public Response verifySessionCookie(@CookieParam("session") Cookie cookie) {
  String sessionCookie = cookie.getValue();
  try {
    // Verify the session cookie. In this case an additional check is added to detect
    // if the user's Firebase session was revoked, user deleted/disabled, etc.
    final boolean checkRevoked = true;
    FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(
        sessionCookie, checkRevoked);
    return serveContentForUser(decodedToken);
  } catch (FirebaseAuthException e) {
    // Session cookie is unavailable, invalid or revoked. Force user to login.
    return Response.temporaryRedirect(URI.create("/login")).build();
  }
}
 
Example #4
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleCookieParameters() throws Exception {
    Class<?>[] argType = {String.class, String.class, Cookie.class};
    Method m = Customer.class.getMethod("testMultipleCookieParam", argType);
    Message messageImpl = createMessage();
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.add("Cookie", "c1=c1Value; c2=c2Value");
    headers.add("Cookie", "c3=c3Value");
    messageImpl.put(Message.PROTOCOL_HEADERS, headers);
    List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m,
                                                           new ClassResourceInfo(Customer.class)),
                                                       null,
                                                       messageImpl);
    assertEquals(3, params.size());
    assertEquals("c1Value", params.get(0));
    assertEquals("c2Value", params.get(1));
    assertEquals("c3Value", ((Cookie)params.get(2)).getValue());
}
 
Example #5
Source File: ThirdEyeAuthFilter.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private boolean isAuthenticated(ContainerRequestContext containerRequestContext, ThirdEyePrincipal principal) {
  Map<String, Cookie> cookies = containerRequestContext.getCookies();

  if (cookies != null && cookies.containsKey(AuthResource.AUTH_TOKEN_NAME)) {
    String sessionKey = cookies.get(AuthResource.AUTH_TOKEN_NAME).getValue();
    if (sessionKey.isEmpty()) {
      LOG.error("Empty sessionKey. Skipping.");
    } else {
      SessionDTO sessionDTO = this.sessionDAO.findBySessionKey(sessionKey);
      if (sessionDTO != null && System.currentTimeMillis() < sessionDTO.getExpirationTime()) {
        // session exist in database and has not expired
        principal.setName(sessionDTO.getPrincipal());
        principal.setSessionKey(sessionKey);
        LOG.info("Found valid session {} for user {}", sessionDTO.getSessionKey(), sessionDTO.getPrincipal());
        return true;
      }
    }
  }
  return false;
}
 
Example #6
Source File: HttpHeadersImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Map<String, Cookie> getCookies() {
    List<String> values = headers.get(HttpHeaders.COOKIE);
    if (values == null || values.isEmpty()) {
        return Collections.emptyMap();
    }

    Map<String, Cookie> cl = new HashMap<>();
    for (String value : values) {
        if (value == null) {
            continue;
        }


        List<String> cs = getHeaderValues(HttpHeaders.COOKIE, value,
                                          getCookieSeparator(value));
        for (String c : cs) {
            Cookie cookie = Cookie.valueOf(c);
            cl.put(cookie.getName(), cookie);
        }
    }
    return cl;
}
 
Example #7
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm, boolean checkActive) {
    Cookie cookie = CookieHelper.getCookie(session.getContext().getRequestHeaders().getCookies(), KEYCLOAK_IDENTITY_COOKIE);
    if (cookie == null || "".equals(cookie.getValue())) {
        logger.debugv("Could not find cookie: {0}", KEYCLOAK_IDENTITY_COOKIE);
        return null;
    }

    String tokenString = cookie.getValue();
    AuthResult authResult = verifyIdentityToken(session, realm, session.getContext().getUri(), session.getContext().getConnection(), checkActive, false, true, tokenString, session.getContext().getRequestHeaders(), VALIDATE_IDENTITY_COOKIE);
    if (authResult == null) {
        expireIdentityCookie(realm, session.getContext().getUri(), session.getContext().getConnection());
        expireOldIdentityCookie(realm, session.getContext().getUri(), session.getContext().getConnection());
        return null;
    }
    authResult.getSession().setLastSessionRefresh(Time.currentTime());
    return authResult;
}
 
Example #8
Source File: RuntimeDelegateImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateHeaderProvider() throws Exception {
    assertSame(MediaTypeHeaderProvider.class,
               new RuntimeDelegateImpl().
                   createHeaderDelegate(MediaType.class).getClass());
    assertSame(EntityTagHeaderProvider.class,
               new RuntimeDelegateImpl().
                   createHeaderDelegate(EntityTag.class).getClass());
    assertSame(CacheControlHeaderProvider.class,
               new RuntimeDelegateImpl().
                   createHeaderDelegate(CacheControl.class).getClass());
    assertSame(CookieHeaderProvider.class,
               new RuntimeDelegateImpl().
                   createHeaderDelegate(Cookie.class).getClass());
    assertSame(NewCookieHeaderProvider.class,
               new RuntimeDelegateImpl().
                   createHeaderDelegate(NewCookie.class).getClass());
}
 
Example #9
Source File: RangerUgSyncRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse post(String relativeURL, Map<String, String> params, Object obj, Cookie sessionId)
		throws Exception {
	ClientResponse response = null;
	int startIndex = getLastKnownActiveUrlIndex();
	int currentIndex = 0;

	for (int index = 0; index < getConfiguredURLs().size(); index++) {
		try {
			currentIndex = (startIndex + index) % getConfiguredURLs().size();

			WebResource webResource = createWebResourceForCookieAuth(currentIndex, relativeURL);
			webResource = setQueryParams(webResource, params);
			WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId);
			response = br.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON)
					.post(ClientResponse.class, toJson(obj));
			if (response != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException e) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + getConfiguredURLs().get(currentIndex));
			processException(index, e);
		}
	}
	return response;
}
 
Example #10
Source File: UserInfoContextProvider.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
private Optional<UserInfoImpl> tryAutoLogin(ContainerRequestContext request, SessionInfo session) {
    Cookie cookie = request.getCookies().get(userWebOptions.autoLoginCookie);
    if (cookie != null) {
        try {
            TokenLoginRequest authenticationRequest = new TokenLoginRequest();
            authenticationRequest.token = cookie.getValue();
            LoginResponse authenticationResponse = userWebService.login(authenticationRequest);
            UserInfoImpl user = user(authenticationResponse.user);
            session.put(SESSION_USER_ID, user.id());
            return Optional.of(user);
        } catch (Throwable e) {
            logger.warn("invalid auto login token cookie, value={}", cookie.getValue());
        }
    }
    return Optional.empty();
}
 
Example #11
Source File: OpenAPIResourceController.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
@Override
public Response apply(ContainerRequestContext arg0) {
    OpenAPISpecFilter 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();
        // since https://github.com/swagger-api/swagger-inflector/issues/305 filtering of inflector extensions is handled at init time by ExtensionsUtils, and VendorSpecFilter is not needed anymore
        return Response.ok().entity(getOpenAPI()).build();
    }
    return Response.ok().entity(getOpenAPI()).build();
}
 
Example #12
Source File: ClientInfoContextProvider.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public ClientInfo get() {
    ClientInfo clientInfo = (ClientInfo) context.getProperty("__client_info");
    if (clientInfo == null) {
        String clientId;
        Map<String, Cookie> cookies = headers.getCookies();
        if (cookies.containsKey(webOptions.cookie.clientId)) {
            clientId = cookies.get(webOptions.cookie.clientId).getValue();
        } else {
            clientId = UUID.randomUUID().toString();
        }
        String language;
        if (cookies.containsKey(webOptions.cookie.language)) {
            language = cookies.get(webOptions.cookie.language).getValue();
        } else {
            language = app.language();
        }
        if (!app.supportLanguages().contains(language)) {
            language = app.language();
        }
        clientInfo = new ClientInfoImpl(clientId, language, context.getHeaderString("X-Client-IP"));
        context.setProperty("__client_info", clientInfo);
    }
    return clientInfo;
}
 
Example #13
Source File: RangerRESTClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public ClientResponse put(String relativeURL, Object request, Cookie sessionId) throws Exception {
	ClientResponse response = null;
	int startIndex = this.lastKnownActiveUrlIndex;
	int currentIndex = 0;

	for (int index = 0; index < configuredURLs.size(); index++) {
		try {
			currentIndex = (startIndex + index) % configuredURLs.size();

			WebResource webResource = createWebResourceForCookieAuth(currentIndex, relativeURL);
			WebResource.Builder br = webResource.getRequestBuilder().cookie(sessionId);
			response = br.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).type(RangerRESTUtils.REST_MIME_TYPE_JSON)
					.put(ClientResponse.class, toJson(request));
			if (response != null) {
				setLastKnownActiveUrlIndex(currentIndex);
				break;
			}
		} catch (ClientHandlerException e) {
			LOG.warn("Failed to communicate with Ranger Admin, URL : " + configuredURLs.get(currentIndex));
			processException(index, e);
		}
	}
	return response;
}
 
Example #14
Source File: AuthenticationService.java    From query2report with GNU General Public License v3.0 6 votes vote down vote up
@Path("/logout")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response logoutUser(@CookieParam("Q2R_AUTH_INFO") Cookie cookie){
	String cookieValue = cookie.getValue();
	String tokenPatterns[] = cookieValue.split("_0_");
	
	if(tokenPatterns.length!=3)
		return Response.serverError().entity("Corrupt Token").build();
	
	logger.info("Logging out user "+tokenPatterns[0]);
	try{
		boolean validToken = UserManager.getUserManager().validateToken(tokenPatterns[0], cookieValue);
		if(validToken){
			UserManager.getUserManager().logoutUser(tokenPatterns[0]);
			return Response.ok("User "+tokenPatterns[0]+" logged out.").build();
		}else{
			return Response.serverError().entity("Logout failed").status(Response.Status.UNAUTHORIZED).build();
		}
	}catch(Exception e){
		return Response.serverError().entity("Logout failed").build();
	}
}
 
Example #15
Source File: CookieHeaderDelegate.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String toString(Cookie cookie) {
    if (cookie == null) {
        throw new IllegalArgumentException();
    }
    StringBuilder sb = new StringBuilder();

    sb.append("$Version=").append(cookie.getVersion()).append(';');

    sb.append(cookie.getName()).append('=').append(addQuotesIfHasWhitespace(cookie.getValue()));

    if (cookie.getDomain() != null) {
        sb.append(';').append("$Domain=").append(addQuotesIfHasWhitespace(cookie.getDomain()));
    }

    if (cookie.getPath() != null) {
        sb.append(';').append("$Path=").append(addQuotesIfHasWhitespace(cookie.getPath()));
    }

    return sb.toString();
}
 
Example #16
Source File: UserAuthFactory.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<User> authenticate(Cookie sessionCookie) throws AuthenticationException {
  Optional<User> user = cookieAuthenticator.authenticate(sessionCookie);
  if (!user.isPresent()) {
    logger.info("Invalid session cookie");
  }
  return user;
}
 
Example #17
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String getSessionIdFromSessionCookie(KeycloakSession session) {
    Cookie cookie = getCookie(session.getContext().getRequestHeaders().getCookies(), KEYCLOAK_SESSION_COOKIE);
    if (cookie == null || "".equals(cookie.getValue())) {
        logger.debugv("Could not find cookie: {0}", KEYCLOAK_SESSION_COOKIE);
        return null;
    }

    String[] parts = cookie.getValue().split("/", 3);
    if (parts.length != 3) {
        logger.debugv("Cannot parse session value from: {0}", KEYCLOAK_SESSION_COOKIE);
        return null;
    }
    return parts[2];
}
 
Example #18
Source File: QuarkusWelcomeResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void csrfCheck(final MultivaluedMap<String, String> formData) {
    String formStateChecker = formData.getFirst("stateChecker");
    Cookie cookie = headers.getCookies().get(KEYCLOAK_STATE_CHECKER);
    if (cookie == null) {
        throw new ForbiddenException();
    }

    String cookieStateChecker = cookie.getValue();

    if (cookieStateChecker == null || !cookieStateChecker.equals(formStateChecker)) {
        throw new ForbiddenException();
    }
}
 
Example #19
Source File: CookieAuthenticator.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Override public Optional<User> authenticate(Cookie cookie) {
  User user = null;

  if (cookie != null) {
    Optional<UserCookieData> cookieData = getUserCookieData(cookie);
    if (cookieData.isPresent()) {
      user = cookieData.get().getUser();
    }
  }

  return Optional.ofNullable(user);
}
 
Example #20
Source File: AlmApiStub.java    From alm-rest-api with GNU General Public License v3.0 5 votes vote down vote up
private void removeCookie(Cookie cookie)
{
    synchronized(this)
    {
        if (cookies.contains(cookie.getValue()))
        {
            cookies.remove(cookie.getValue());
        }
    }
}
 
Example #21
Source File: AbstractServiceProviderFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ResponseState getValidResponseState(Cookie securityContextCookie,
                                              Message m) {
    if (securityContextCookie == null) {
        // most likely it means that the user has not been offered
        // a chance to get logged on yet, though it might be that the browser
        // has removed an expired cookie from its cache; warning is too noisy in the
        // former case
        reportTrace("MISSING_RESPONSE_STATE");
        return null;
    }
    String contextKey = securityContextCookie.getValue();

    ResponseState responseState = getStateProvider().getResponseState(contextKey);

    if (responseState == null) {
        reportError("MISSING_RESPONSE_STATE");
        return null;
    }
    if (isStateExpired(responseState.getCreatedAt(), responseState.getExpiresAt())) {
        reportError("EXPIRED_RESPONSE_STATE");
        getStateProvider().removeResponseState(contextKey);
        return null;
    }
    String webAppContext = getWebAppContext(m);
    if (webAppDomain != null
        && (responseState.getWebAppDomain() == null
            || !webAppDomain.equals(responseState.getWebAppDomain()))
        || responseState.getWebAppContext() == null
        || !webAppContext.equals(responseState.getWebAppContext())) {
        getStateProvider().removeResponseState(contextKey);
        reportError("INVALID_RESPONSE_STATE");
        return null;
    }
    if (responseState.getAssertion() == null) {
        reportError("INVALID_RESPONSE_STATE");
        return null;
    }
    return responseState;
}
 
Example #22
Source File: AuthenticationFilterTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnSessionIfAuthCookieIsFoundAndSessionHasNotExpired() {
	when(configuration.getSessionExpiryTimeInSecs()).thenReturn(100L);
	Map<String, Cookie> cookies = new HashMap<String, Cookie>();
	String sessionId = UUID.randomUUID().toString();
	cookies.put(AuthenticationFilter.AUTH_COOKIE, new Cookie(AuthenticationFilter.AUTH_COOKIE, sessionId));
	when(context.getCookies()).thenReturn(cookies);
	Session session = mock(Session.class);
	when(session.hasExpired(100)).thenReturn(false);
	when(sessionStore.getSession(sessionId)).thenReturn(session);
	assertEquals(filter.getSession(context, true), session);
	verify(sessionStore, never()).createSession(any(String.class));
}
 
Example #23
Source File: SSEClientRule.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Checks the headers for the session cookie and extracts it when received, so we can use it on subsequent
 * tests / waits within the same session.
 */
private void checkResponseForCookie(Response httpResponse) {
    List<Object> cookies = httpResponse.getHeaders().get("Set-Cookie");

    if (cookies != null) {
        for (Object rawCookieObj : cookies) {
            String rawCookie = rawCookieObj.toString();
            if (rawCookie.toUpperCase().contains("JSESSIONID")) {
                this.sessionCookie = Cookie.valueOf(rawCookie);
                break;
            }
        }
    }
}
 
Example #24
Source File: BeanParamFilter.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException {
    String body = (String)clientRequestContext.getEntity();
    String query = clientRequestContext.getUri().getQuery();
    Cookie cookie = clientRequestContext.getCookies().get("cookie");
    String cookieValue = cookie==null?"null":cookie.getValue();
    String header = clientRequestContext.getHeaderString("MyHeader");
    clientRequestContext.abortWith(Response.ok(query + " " + cookieValue + " " + header + " " + body).build());
}
 
Example #25
Source File: JaxrsOAuthClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void checkStateCookie(UriInfo uriInfo, HttpHeaders headers) {
    Cookie stateCookie = headers.getCookies().get(stateCookieName);
    if (stateCookie == null) throw new BadRequestException("state cookie not set");
    String state = uriInfo.getQueryParameters().getFirst(OAuth2Constants.STATE);
    if (state == null) throw new BadRequestException("state parameter was null");
    if (!state.equals(stateCookie.getValue())) {
        throw new BadRequestException("state parameter invalid");
    }
}
 
Example #26
Source File: UserResource.java    From tastjava with MIT License 5 votes vote down vote up
@GET
@Path("/logout")
@Produces(MediaType.TEXT_PLAIN)
public Response logout(@CookieParam("jwt-authToken") Cookie cookie) {
    if (cookie != null) {
        NewCookie newCookie = new NewCookie("jwt-authToken", "","/", "", "comment", 0, false);
        return Response.ok("OK").cookie(newCookie).build();
    }
    return Response.ok("OK - No session").build();
}
 
Example #27
Source File: DefaultLocaleSelectorProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Locale getLocaleCookieSelection(RealmModel realm, HttpHeaders httpHeaders) {
    if (httpHeaders == null) {
        return null;
    }

    Cookie localeCookie = httpHeaders.getCookies().get(LOCALE_COOKIE);
    if (localeCookie == null) {
        return null;
    }

    return findLocale(realm, localeCookie.getValue());
}
 
Example #28
Source File: JwtAuthFilter.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
private Optional<String> getTokenFromCookie(ContainerRequestContext requestContext) {
    final Map<String, Cookie> cookies = requestContext.getCookies();

    if (cookieName != null && cookies.containsKey(cookieName)) {
        final Cookie tokenCookie = cookies.get(cookieName);
        final String rawToken = tokenCookie.getValue();
        return Optional.of(rawToken);
    }

    return Optional.empty();
}
 
Example #29
Source File: AuthenticationFilterTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCreateSessionIfAuthCookieIsNotFoundAndCreateIsFalse() {
	when(context.getCookies()).thenReturn(Maps.<String, Cookie>newHashMap());
	Session session = mock(Session.class);
	when(sessionStore.createSession(any(String.class))).thenReturn(session);
	assertNull(filter.getSession(context, false));
}
 
Example #30
Source File: JaxRsParameterProviderTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void onLongCookieShouldReturnThisInstance() throws Exception {
	// GIVEN
	when(requestContext.getCookies()).thenReturn(Collections.singletonMap("sid", new Cookie("sid", "123")));
	when(objectMapper.readValue(any(String.class), any(Class.class))).thenReturn(123L);

	// WHEN
	Object result = sut.provide(testMethod, 4);

	// THEN
	verify(requestContext).getCookies();
	verify(objectMapper).readValue("123", Long.class);
	assertThat(result).isEqualTo(123L);
}