Java Code Examples for javax.ws.rs.core.Cookie#getValue()

The following examples show how to use javax.ws.rs.core.Cookie#getValue() . 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: UserAdminInterceptor.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(options.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 2
Source File: UserAdminAJAXController.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Path("/login")
@POST
public Response login(LoginAJAXRequest loginAJAXRequest) {
    captchaCode.validate(loginAJAXRequest.captchaCode);
    LoginRequest loginRequest = new LoginRequest();
    loginRequest.username = loginAJAXRequest.username;
    loginRequest.password = loginAJAXRequest.password;
    loginRequest.autoLogin = loginAJAXRequest.autoLogin;
    LoginResponse authenticationResponse = userWebService.login(loginRequest);

    sessionInfo.put("USER_ID", authenticationResponse.user.id);

    LoginAJAXResponse loginAJAXResponse = new LoginAJAXResponse();
    Cookie cookie = requestContext.getCookies().get("fromURL");
    loginAJAXResponse.fromURL = cookie == null ? null : cookie.getValue();
    String autoLoginCookie = Boolean.TRUE.equals(loginAJAXRequest.autoLogin) ? authenticationResponse.autoLoginToken : null;
    return Response.ok().entity(loginAJAXResponse).cookie(new NewCookie(userAdminOptions.autoLoginCookie, autoLoginCookie, "/", null, null, Integer.MAX_VALUE, false))
        .build();
}
 
Example 3
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 4
Source File: AuthenticationDaoImpl.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 5
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 6
Source File: ClientSideState.java    From syndesis with Apache License 2.0 5 votes vote down vote up
<T> TimestampedState<T> restoreWithTimestamp(final Cookie cookie, final Class<T> type) {
    final String value = cookie.getValue();

    final String[] parts = value.split("\\|", 5);

    final byte[] atime = DECODER.decode(parts[1]);

    final long atimeLong = atime(atime);

    if (atimeLong + timeout < timeSource.getAsLong()) {
        throw new IllegalArgumentException("Given value has timed out at: " + Instant.ofEpochSecond(atimeLong));
    }

    final byte[] tid = DECODER.decode(parts[2]);
    if (!MessageDigest.isEqual(tid, edition.tid)) {
        throw new IllegalArgumentException(String.format("Given TID `%s`, mismatches current TID `%s`",
            new BigInteger(tid).toString(16), new BigInteger(edition.tid).toString(16)));
    }

    final KeySource keySource = edition.keySource();
    final int lastSeparatorIdx = value.lastIndexOf('|');
    final byte[] mac = DECODER.decode(parts[4]);
    final byte[] calculated = mac(edition.authenticationAlgorithm, value.substring(0, lastSeparatorIdx),
        keySource.authenticationKey());
    if (!MessageDigest.isEqual(mac, calculated)) {
        throw new IllegalArgumentException("Cookie value fails authenticity check");
    }

    final byte[] iv = DECODER.decode(parts[3]);
    final byte[] encrypted = DECODER.decode(parts[0]);
    final byte[] clear = decrypt(edition.encryptionAlgorithm, iv, encrypted, keySource.encryptionKey());

    @SuppressWarnings("unchecked")
    final T ret = (T) deserialization.apply(type, clear);

    return new TimestampedState<>(ret, atimeLong);
}
 
Example 7
Source File: JwtCookieAuthenticationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String getEncodedJwtToken(ContainerRequestContext requestContext) {
    Cookie cookie = requestContext.getCookies().get(cookieName);
    if (cookie == null || cookie.getValue() == null) {
        throw new JoseException("JWT cookie is not available");
    }
    return cookie.getValue();
}
 
Example 8
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Object processCookieParam(Message m, String cookieName,
                          Class<?> pClass, Type genericType,
                          Annotation[] paramAnns, String defaultValue) {
    Cookie c = new HttpHeadersImpl(m).getCookies().get(cookieName);

    if (c == null && defaultValue != null) {
        c = Cookie.valueOf(cookieName + '=' + defaultValue);
    }
    if (c == null) {
        return null;
    }

    if (pClass.isAssignableFrom(Cookie.class)) {
        return c;
    }
    String value = InjectionUtils.isSupportedCollectionOrArray(pClass)
        && InjectionUtils.getActualType(genericType) == Cookie.class
        ? c.toString() : c.getValue();
    return InjectionUtils.createParameterObject(Collections.singletonList(value),
                                                pClass,
                                                genericType,
                                                paramAnns,
                                                null,
                                                false,
                                                ParameterType.COOKIE,
                                                m);
}
 
Example 9
Source File: RestSecurityInterceptor.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	
	// get our token...		
	Map<String, Cookie> cookies = requestContext.getCookies();
	
	Cookie authTokenCookie = cookies.get( "authToken" );
	if( authTokenCookie == null )
	{
		requestContext.abortWith(ACCESS_DENIED );
		return;			
	}
	
	String authToken = authTokenCookie.getValue();
	try {
		
		if( ! AuthToken.validateToken(configProps, authToken) )
		{
			requestContext.abortWith(ACCESS_DENIED );
			return;	
		}
	} 
	catch (Exception e) {

		e.printStackTrace();
		requestContext.abortWith(ACCESS_DENIED );
		return;
	}

	// if the token is good, just return...
	
}
 
Example 10
Source File: WebStatFilter.java    From ameba with MIT License 5 votes vote down vote up
/**
 * <p>getPrincipal.</p>
 *
 * @param httpRequest a {@link javax.ws.rs.container.ContainerRequestContext} object.
 * @return a {@link java.lang.String} object.
 */
public String getPrincipal(ContainerRequestContext httpRequest) {
    if (principalCookieName != null && httpRequest.getCookies().size() > 0) {
        Map<String, Cookie> cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies.values()) {
            if (principalCookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
    }

    return null;
}
 
Example 11
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 12
Source File: TokenFactory.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean isRealOwnerOfToken(Cookie tokenCookie) throws Exception {
    LOGGER.debug("HttpContext : " + this.getContainerRequest().getPath(true) + " Cookie : " + tokenCookie);
    BasicToken token = new BasicToken(tokenCookie.getValue());
    String hash = generateAttributesHash();
    return hash.equals(token.getAttributesHash());

}
 
Example 13
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 14
Source File: WelcomeResource.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 15
Source File: RestartLoginCookie.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static AuthenticationSessionModel restartSession(KeycloakSession session, RealmModel realm,
                                                        RootAuthenticationSessionModel rootSession, String expectedClientId) throws Exception {
    Cookie cook = session.getContext().getRequestHeaders().getCookies().get(KC_RESTART);
    if (cook ==  null) {
        logger.debug("KC_RESTART cookie doesn't exist");
        return null;
    }
    String encodedCookie = cook.getValue();

    RestartLoginCookie cookie = session.tokens().decode(encodedCookie, RestartLoginCookie.class);
    if (cookie == null) {
        logger.debug("Failed to verify encoded RestartLoginCookie");
        return null;
    }

    ClientModel client = realm.getClientByClientId(cookie.getClientId());
    if (client == null) return null;

    // Restart just if client from cookie matches client from the URL.
    if (!client.getClientId().equals(expectedClientId)) {
        logger.debugf("Skip restarting from the KC_RESTART. Clients doesn't match: Cookie client: %s, Requested client: %s", client.getClientId(), expectedClientId);
        return null;
    }

    // Need to create brand new session and setup cookie
    if (rootSession == null) {
        rootSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true);
    }

    AuthenticationSessionModel authSession = rootSession.createAuthenticationSession(client);
    authSession.setProtocol(cookie.getAuthMethod());
    authSession.setRedirectUri(cookie.getRedirectUri());
    authSession.setAction(cookie.getAction());
    for (Map.Entry<String, String> entry : cookie.getNotes().entrySet()) {
        authSession.setClientNote(entry.getKey(), entry.getValue());
    }

    return authSession;
}
 
Example 16
Source File: UserAJAXController.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private LoginAJAXResponse loginAJAXResponse(String userId) {
    LoginAJAXResponse response = new LoginAJAXResponse();
    response.userId = userId;
    Cookie url = requestContext.getCookies().get(COOKIE_FROM_URL);
    if (url != null) {
        response.fromURL = url.getValue();
    }
    return response;
}
 
Example 17
Source File: TestingResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/get-sso-cookie")
@Produces(MediaType.APPLICATION_JSON)
public String getSSOCookieValue() {
    Map<String, Cookie> cookies = request.getHttpHeaders().getCookies();
    Cookie cookie = CookieHelper.getCookie(cookies, AuthenticationManager.KEYCLOAK_IDENTITY_COOKIE);
    if (cookie == null) return null;
    return cookie.getValue();
}
 
Example 18
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String getRememberMeUsername(RealmModel realm, HttpHeaders headers) {
    if (realm.isRememberMe()) {
        Cookie cookie = headers.getCookies().get(AuthenticationManager.KEYCLOAK_REMEMBER_ME);
        if (cookie != null) {
            String value = cookie.getValue();
            String[] s = value.split(":");
            if (s[0].equals("username") && s.length == 2) {
                return s[1];
            }
        }
    }
    return null;
}
 
Example 19
Source File: TokenSecurityContextFilter.java    From openscoring with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	SecurityContext requestSecurityContext = requestContext.getSecurityContext();

	SecurityContext securityContext = new SecurityContext(){

		@Override
		public Principal getUserPrincipal(){
			return Anonymous.INSTANCE;
		}

		@Override
		public boolean isUserInRole(String role){
			String token = getToken();

			String roleToken;

			switch(role){
				case Roles.USER:
					roleToken = getUserToken();
					break;
				case Roles.ADMIN:
					roleToken = getAdminToken();
					break;
				default:
					return false;
			}

			return (roleToken).equals(token) || (roleToken).equals("");
		}

		@Override
		public boolean isSecure(){
			return requestSecurityContext != null && requestSecurityContext.isSecure();
		}

		@Override
		public String getAuthenticationScheme(){
			return "TOKEN";
		}

		private String getToken(){
			Map<String, Cookie> cookies = requestContext.getCookies();
			MultivaluedMap<String, String> headers = requestContext.getHeaders();

			Cookie tokenCookie = cookies.get("token");
			if(tokenCookie != null){
				return tokenCookie.getValue();
			}

			String authorizationHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
			if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")){
				return authorizationHeader.substring("Bearer ".length());
			}

			return null;
		}
	};

	requestContext.setSecurityContext(securityContext);
}
 
Example 20
Source File: AbstractServiceProviderFilter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
protected ResponseState getValidResponseState(Cookie securityContextCookie,
                                              FedizContext fedConfig,
                                              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 = stateManager.getResponseState(contextKey);

    if (responseState == null) {
        reportError("MISSING_RESPONSE_STATE");
        return null;
    }

    if (CookieUtils.isStateExpired(responseState.getCreatedAt(), fedConfig.isDetectExpiredTokens(),
                                   responseState.getExpiresAt(), getStateTimeToLive())) {
        reportError("EXPIRED_RESPONSE_STATE");
        stateManager.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())) {
        stateManager.removeResponseState(contextKey);
        reportError("INVALID_RESPONSE_STATE");
        return null;
    }
    if (responseState.getAssertion() == null) {
        reportError("INVALID_RESPONSE_STATE");
        return null;
    }
    return responseState;
}