javax.ws.rs.core.NewCookie Java Examples

The following examples show how to use javax.ws.rs.core.NewCookie. 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: UserAJAXController.java    From jweb-cms with GNU Affero General Public License v3.0 7 votes vote down vote up
@Path("/login")
@POST
public Response login(LoginAJAXRequest loginAJAXRequest) throws IOException {
    captchaCode.validate(loginAJAXRequest.captchaCode);

    LoginRequest authenticationRequest = new LoginRequest();
    authenticationRequest.username = loginAJAXRequest.username;
    authenticationRequest.password = loginAJAXRequest.password;
    authenticationRequest.autoLogin = loginAJAXRequest.autoLogin;

    LoginResponse authenticationResponse = userWebService.login(authenticationRequest);
    UserResponse user = authenticationResponse.user;
    sessionInfo.put(UserInfoContextProvider.SESSION_USER_ID, user.id);

    if (Boolean.TRUE.equals(loginAJAXRequest.autoLogin)) {
        return Response.ok().entity(loginAJAXResponse(user.id))
            .cookie(new NewCookie(userWebOptions.autoLoginCookie, authenticationResponse.autoLoginToken, "/", null, null, userWebOptions.autoLoginMaxAge, false))
            .cookie(Cookies.removeCookie(COOKIE_FROM_URL)).build();
    } else {
        return Response.ok(loginAJAXResponse(user.id)).cookie(Cookies.removeCookie(COOKIE_FROM_URL)).build();
    }
}
 
Example #2
Source File: ConnectorCredentialHandler.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #3
Source File: AuthRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void loginAuthValidNoPrincipalsTest() throws Exception {
    // Setup:
    String authorization = USERNAME + ":" + PASSWORD;
    when(RestSecurityUtils.authenticateUser(eq("mobi"), any(Subject.class), eq(USERNAME), eq(PASSWORD), eq(mobiConfiguration))).thenReturn(true);

    Response response = target().path("session").request()
            .header("Authorization", "Basic " + Base64.encode(authorization.getBytes())).post(Entity.json(""));
    assertEquals(response.getStatus(), 401);
    verifyStatic();
    RestSecurityUtils.authenticateUser(eq("mobi"), any(Subject.class), eq(USERNAME), eq(PASSWORD), eq(mobiConfiguration));
    verify(tokenManager, never()).generateAuthToken(anyString());
    verify(engineManager, times(0)).getUserRoles(anyString());
    Map<String, NewCookie> cookies = response.getCookies();
    assertEquals(0, cookies.size());
}
 
Example #4
Source File: AuthRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void loginAuthValidTest() throws Exception {
    // Setup:
    String authorization = USERNAME + ":" + PASSWORD;

    Response response = target().path("session").request()
            .header("Authorization", "Basic " + Base64.encode(authorization.getBytes())).post(Entity.json(""));
    assertEquals(response.getStatus(), 200);
    verifyStatic();
    RestSecurityUtils.authenticateUser(eq("mobi"), any(Subject.class), eq(USERNAME), eq(PASSWORD), eq(mobiConfiguration));
    verify(tokenManager).generateAuthToken(USERNAME);
    verify(engineManager).getUserRoles(USERNAME);
    Map<String, NewCookie> cookies = response.getCookies();
    assertTrue(cookies.containsKey(TOKEN_NAME));
    assertEquals(USERNAME, cookies.get(TOKEN_NAME).getValue());
    try {
        JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
        assertEquals(removeWhitespace(VALID_USER), removeWhitespace(result.toString()));
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example #5
Source File: AuthenticateResource.java    From clouditor with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
  var payload = new LoginResponse();

  if (!service.verifyLogin(request)) {
    throw new NotAuthorizedException("Invalid user and/or password");
  }

  var user = PersistenceManager.getInstance().getById(User.class, request.getUsername());

  payload.setToken(service.createToken(user));

  // TODO: max age, etc.
  return Response.ok(payload).cookie(new NewCookie("authorization", payload.getToken())).build();
}
 
Example #6
Source File: StockQuoteService.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #7
Source File: AbstractSecuredLocalService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public Response redirect(UriInfo uriInfo, String redirectUri) {
    String state = getStateCode();
    String scopeParam = TokenUtil.attachOIDCScope(scope);

    UriBuilder uriBuilder = UriBuilder.fromUri(authUrl)
            .queryParam(OAuth2Constants.CLIENT_ID, clientId)
            .queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
            .queryParam(OAuth2Constants.STATE, state)
            .queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
            .queryParam(OAuth2Constants.SCOPE, scopeParam);

    URI url = uriBuilder.build();

    NewCookie cookie = new NewCookie(getStateCookieName(), state, getStateCookiePath(uriInfo), null, null, -1, isSecure, true);
    logger.debug("NewCookie: " + cookie.toString());
    logger.debug("Oauth Redirect to: " + url);
    return Response.status(302)
            .location(url)
            .cookie(cookie).build();
}
 
Example #8
Source File: AuthRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void loginCredValidTest() throws Exception {
    Response response = target().path("session").queryParam("username", USERNAME).queryParam("password", PASSWORD).request().post(Entity.json(""));
    assertEquals(response.getStatus(), 200);
    verifyStatic();
    RestSecurityUtils.authenticateUser(eq("mobi"), any(Subject.class), eq(USERNAME), eq(PASSWORD), eq(mobiConfiguration));
    verify(tokenManager).generateAuthToken(USERNAME);
    verify(engineManager).getUserRoles(USERNAME);
    Map<String, NewCookie> cookies = response.getCookies();
    assertTrue(cookies.containsKey(TOKEN_NAME));
    assertEquals(USERNAME, cookies.get(TOKEN_NAME).getValue());
    try {
        JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
        assertEquals(removeWhitespace(VALID_USER), removeWhitespace(result.toString()));
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example #9
Source File: AuthenticationResourceHandler.java    From datacollector with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: CreateQuerySessionIDFilterTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Test
public void filterNoQueryId() throws Exception {
    EasyMock.expect(method.getMethodAnnotations()).andReturn(new Annotation[] {annotation});
    // More method calls due to logging the error about QUERY_ID threadlocal not set.
    EasyMock.expect(method.getResourceClass()).andReturn(null);
    // noinspection ConfusingArgumentToVarargsMethod
    EasyMock.expect(method.getMethod()).andReturn(getClass().getMethod("filterNoQueryId", null));
    replayAll();
    
    CreateQuerySessionIDFilter.QUERY_ID.set(null);
    filter.filter(request, response);
    
    NewCookie responseCookie = (NewCookie) response.getHeaders().getFirst("Set-Cookie");
    assertNotNull("No cookie present when we should have one.", responseCookie);
    assertEquals("query-session-id", responseCookie.getName());
    assertEquals("/test/path/", responseCookie.getPath());
    
    verifyAll();
}
 
Example #11
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 #12
Source File: AuthRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getCurrentUserTest() throws Exception {
    Response response = target().path("session").request().get();
    assertEquals(response.getStatus(), 200);
    verify(tokenManager).getTokenString(any(ContainerRequestContext.class));
    verify(tokenManager).verifyToken(TOKEN_STRING);
    verify(tokenManager, never()).generateUnauthToken();
    Map<String, NewCookie> cookies = response.getCookies();
    assertEquals(0, cookies.size());
    try {
        JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
        assertEquals(removeWhitespace(VALID_USER), removeWhitespace(result.toString()));
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example #13
Source File: PlaySessionResource.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@GET
@Path("/client-logout/{redirectUri}")
@UnitOfWork
public Response serviceLogOut(
        @Context UriInfo uriInfo,
        @CookieParam(COOKIE_NAME) String token,
        @PathParam("redirectUri") String redirectUri) {
    sessionStore.deleteSessionByToken(token);
    return Response.seeOther(URI.create(redirectUri))
            .cookie(new NewCookie(
                    COOKIE_NAME,
                    "expired",
                    "/",
                    uriInfo.getBaseUri().getHost(),
                    Cookie.DEFAULT_VERSION,
                    null,
                    (int) Duration.ofDays(7).getSeconds(),
                    new Date(0),
                    false,
                    true))
            .build();
}
 
Example #14
Source File: GrafanaUserDetailsUtil.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * used to create new session with grafana (login with grafana)
 * 
 * @param userName
 * @param password
 * @return
 * @throws InsightsCustomException
 */
private static List<NewCookie> getValidGrafanaSession(String userName, String password)
		throws InsightsCustomException {
	log.debug("Inside getValidGrafanaSession method call");
	JsonObject loginRequestParams = new JsonObject();
	loginRequestParams.addProperty("user", userName);
	loginRequestParams.addProperty("password", password);
	String loginApiUrl = ApplicationConfigProvider.getInstance().getGrafana().getGrafanaEndpoint() + "/login";
	ClientResponse grafanaLoginResponse = RestHandler.doPost(loginApiUrl, loginRequestParams, null);
	log.debug("GrafanaUserDetailsUtil ==== status code {} loginApiUrl {} Grafana responce {} ",
			grafanaLoginResponse.getStatus(), loginApiUrl, grafanaLoginResponse.getEntity(String.class));
	if (grafanaLoginResponse.getStatus() != 200) {
		String response = grafanaLoginResponse.getEntity(String.class);
		log.error("GrafanaUserDetailsUtil ==== unable to getValidGrafanaSession ==== {} response {}",
				grafanaLoginResponse.getStatus(), response);
		throw new InsightsCustomException(" user or password is incorrect ==== ");
	}
	return grafanaLoginResponse.getCookies();
}
 
Example #15
Source File: FirebaseAuthSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/sessionLogin")
@Consumes("application/json")
public Response createSessionCookie(LoginRequest request) {
  // Get the ID token sent by the client
  String idToken = request.getIdToken();
  // Set session expiration to 5 days.
  long expiresIn = TimeUnit.DAYS.toMillis(5);
  SessionCookieOptions options = SessionCookieOptions.builder()
      .setExpiresIn(expiresIn)
      .build();
  try {
    // Create the session cookie. This will also verify the ID token in the process.
    // The session cookie will have the same claims as the ID token.
    String sessionCookie = FirebaseAuth.getInstance().createSessionCookie(idToken, options);
    // Set cookie policy parameters as required.
    NewCookie cookie = new NewCookie("session", sessionCookie /* ... other parameters */);
    return Response.ok().cookie(cookie).build();
  } catch (FirebaseAuthException e) {
    return Response.status(Status.UNAUTHORIZED).entity("Failed to create a session cookie")
        .build();
  }
}
 
Example #16
Source File: FirebaseAuthSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public Response checkAuthTime(String idToken) throws FirebaseAuthException {
  // [START check_auth_time]
  // To ensure that cookies are set only on recently signed in users, check auth_time in
  // ID token before creating a cookie.
  FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);
  long authTimeMillis = TimeUnit.SECONDS.toMillis(
      (long) decodedToken.getClaims().get("auth_time"));

  // Only process if the user signed in within the last 5 minutes.
  if (System.currentTimeMillis() - authTimeMillis < TimeUnit.MINUTES.toMillis(5)) {
    long expiresIn = TimeUnit.DAYS.toMillis(5);
    SessionCookieOptions options = SessionCookieOptions.builder()
        .setExpiresIn(expiresIn)
        .build();
    String sessionCookie = FirebaseAuth.getInstance().createSessionCookie(idToken, options);
    // Set cookie policy parameters as required.
    NewCookie cookie = new NewCookie("session", sessionCookie);
    return Response.ok().cookie(cookie).build();
  }
  // User did not sign in recently. To guard against ID token theft, require
  // re-authentication.
  return Response.status(Status.UNAUTHORIZED).entity("Recent sign in required").build();
  // [END check_auth_time]
}
 
Example #17
Source File: ClientSideStateTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPersistAsInRfcErrata() {
    final ClientSideState clientSideState = new ClientSideState(RFC_EDITION, ClientSideStateTest::rfcTime, ClientSideStateTest::rfcIV,
        ClientSideStateTest::serialize, ClientSideStateTest::deserialize, 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();
}
 
Example #18
Source File: RuntimeDelegateImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public RuntimeDelegateImpl() {
    headerProviders.put(MediaType.class, new MediaTypeHeaderProvider());
    headerProviders.put(CacheControl.class, new CacheControlHeaderProvider());
    headerProviders.put(EntityTag.class, new EntityTagHeaderProvider());
    headerProviders.put(Cookie.class, new CookieHeaderProvider());
    headerProviders.put(NewCookie.class, new NewCookieHeaderProvider());
    headerProviders.put(Link.class, new LinkHeaderProvider());
    headerProviders.put(Date.class, new DateHeaderProvider());
}
 
Example #19
Source File: SessionResource.java    From airpal with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/postlogin")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public Response getLoginNoRemember()
{
    return Response.temporaryRedirect(URI.create("/app")).cookie(new NewCookie("rememberMe", null)).build();
}
 
Example #20
Source File: AuthRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void loginCredNoUsernameTest() throws Exception {
    // Setup:
    String authorization = ":" + PASSWORD;

    Response response = target().path("session").queryParam("password", PASSWORD).request().post(Entity.json(""));
    assertEquals(response.getStatus(), 401);
    verify(tokenManager, never()).generateAuthToken(anyString());
    Map<String, NewCookie> cookies = response.getCookies();
    assertEquals(0, cookies.size());
}
 
Example #21
Source File: TokenEndPointResource.java    From io with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Response responseAuthSuccess(final IAccessToken accessToken, final IRefreshToken refreshToken) {
    JSONObject resp = new JSONObject();
    resp.put(OAuth2Helper.Key.ACCESS_TOKEN, accessToken.toTokenString());
    resp.put(OAuth2Helper.Key.EXPIRES_IN, accessToken.expiresIn());
    if (refreshToken != null) {
        resp.put(OAuth2Helper.Key.REFRESH_TOKEN, refreshToken.toTokenString());
        resp.put(OAuth2Helper.Key.REFRESH_TOKEN_EXPIRES_IN, refreshToken.refreshExpiresIn());
    }
    resp.put(OAuth2Helper.Key.TOKEN_TYPE, OAuth2Helper.Scheme.BEARER);
    ResponseBuilder rb = Response.ok().type(MediaType.APPLICATION_JSON_TYPE);
    if (accessToken.getTarget() != null) {
        resp.put(OAuth2Helper.Key.TARGET, accessToken.getTarget());
        rb.header(HttpHeaders.LOCATION, accessToken.getTarget() + "__auth");
    }

    if (issueCookie) {
        String tokenString = accessToken.toTokenString();
        // dc_cookie_peerとして、ランダムなUUIDを設定する
        String dcCookiePeer = UUID.randomUUID().toString();
        String cookieValue = dcCookiePeer + "\t" + tokenString;
        // ヘッダに返却するdc_cookie値は、暗号化する
        String encodedCookieValue = LocalToken.encode(cookieValue,
                UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(requestURIInfo.getBaseUri())));
        // Cookieのバージョン(0)を指定
        int version = 0;
        String path = getCookiePath();

        // Cookieを作成し、レスポンスヘッダに返却する
        Cookie cookie = new Cookie("dc_cookie", encodedCookieValue, path, requestURIInfo.getBaseUri().getHost(),
                version);
        rb.cookie(new NewCookie(cookie, "", -1, DcCoreConfig.isHttps()));
        // レスポンスボディの"dc_cookie_peer"を返却する
        resp.put("dc_cookie_peer", dcCookiePeer);
    }
    return rb.entity(resp.toJSONString()).build();
}
 
Example #22
Source File: NewCookieHeaderDelegate.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String toString(NewCookie cookie) {
    checkArgument(cookie != null);
    StringBuilder sb = new StringBuilder();
    sb.append(cookie.getName()).append('=').append(addQuotesIfHasWhitespace(cookie.getValue()));

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

    if (cookie.getComment() != null) {
        sb.append(';').append("Comment=").append(addQuotesIfHasWhitespace(cookie.getComment()));
    }

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

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

    if (cookie.getMaxAge() != -1) {
        sb.append(';').append("Max-Age=").append(addQuotesIfHasWhitespace(Integer.toString(cookie.getMaxAge())));
    }

    if (cookie.getExpiry() != null) {
        sb.append(';').append("Expires=");
        sb.append(HeaderHelper.formatDate(cookie.getExpiry()));
    }

    if (cookie.isSecure()) {
        sb.append(';').append("Secure");
    }

    if (cookie.isHttpOnly()) {
        sb.append(';').append("HttpOnly");
    }

    return sb.toString();
}
 
Example #23
Source File: JerseyHttpClient.java    From karate with MIT License 5 votes vote down vote up
@Override
public HttpResponse makeHttpRequest(Entity entity, ScenarioContext context) {
    String method = request.getMethod();
    if ("PATCH".equals(method)) { // http://danofhisword.com/dev/2015/09/04/Jersey-Client-Http-Patch.html
        builder.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    }
    Response resp;
    if (entity != null) {
        resp = builder.method(method, entity);
    } else {
        resp = builder.method(method);
    }
    HttpRequest actualRequest = context.getPrevRequest();
    HttpResponse response = new HttpResponse(actualRequest.getStartTime(), actualRequest.getEndTime());
    byte[] bytes = resp.readEntity(byte[].class);        
    response.setUri(getRequestUri());
    response.setBody(bytes);
    response.setStatus(resp.getStatus());
    for (NewCookie c : resp.getCookies().values()) {
        com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
        cookie.put(DOMAIN, c.getDomain());
        cookie.put(PATH, c.getPath());
        if (c.getExpiry() != null) {
            cookie.put(EXPIRES, c.getExpiry().getTime() + "");
        }
        cookie.put(SECURE, c.isSecure() + "");
        cookie.put(HTTP_ONLY, c.isHttpOnly() + "");
        cookie.put(MAX_AGE, c.getMaxAge() + "");
        response.addCookie(cookie);
    }
    for (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {
        response.putHeader(entry.getKey(), entry.getValue());
    }
    return response;
}
 
Example #24
Source File: OAuthResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@GET
@Path("callback")
public Response callback(@QueryParam("code") String code) {
  var token = retrieveAccessToken(code);

  var user = token.decode(this.engine.getOAuthJwtSecret(), this.engine.getoAuthJwtIssuer());

  if (user == null) {
    // redirect back to the beginning
    return buildRedirect();
  }

  LOGGER.info("Decoded access token as user {}", user.getUsername());

  // try to find the user
  var ref = PersistenceManager.getInstance().getById(User.class, user.getId());

  if (ref == null) {
    service.createUser(user);
  }

  // issue token for our API
  var payload = new LoginResponse();

  payload.setToken(service.createToken(user));

  // TODO: max age, etc.
  /* angular is particular about the hash! it needs to be included.
  we cannot use UriBuilder, since it will remove the hash */
  var uri = URI.create("/#?token=" + payload.getToken());

  return Response.temporaryRedirect(uri)
      .cookie(new NewCookie("authorization", payload.getToken()))
      .build();
}
 
Example #25
Source File: SimpleTokenManagerTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void createSecureTokenNewCookieTest() {
    NewCookie result = manager.createSecureTokenNewCookie(jwt);
    assertEquals(SimpleTokenManager.TOKEN_NAME, result.getName());
    assertEquals(MOBI_TOKEN, result.getValue());
    assertTrue(result.isSecure());
    assertEquals("/", result.getPath());
}
 
Example #26
Source File: ResponseImpl.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Response build() {
    MultivaluedMap<String, Object> httpHeaders = new CaselessMultivaluedMap<>(headers);
    if (!cookies.isEmpty()) {
        for (NewCookie c : cookies.values()) {
            httpHeaders.add(SET_COOKIE, c);
        }
    }
    Response response = new ResponseImpl(status, entity, entityAnnotations, httpHeaders);
    reset();
    return response;
}
 
Example #27
Source File: NewCookieHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromComplexString() {
    NewCookie c = NewCookie.valueOf(
                  "foo=bar;Comment=comment;Path=path;Max-Age=10;Domain=domain;Secure;Version=1");
    assertTrue("bar".equals(c.getValue())
               && "foo".equals(c.getName())
               && 1 == c.getVersion()
               && "path".equals(c.getPath())
               && "domain".equals(c.getDomain())
               && "comment".equals(c.getComment())
               && 10 == c.getMaxAge());
}
 
Example #28
Source File: ResponseImplTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void parsesSetCookieHeader() throws Exception {
    MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();

    headers.put(SET_COOKIE, newArrayList("name=andrew",
                                         "company=codenvy;version=1;paTh=/path;Domain=codenvy.com;comment=\"comment\";max-age=300;HttpOnly;secure"));
    ResponseImpl response = new ResponseImpl(200, "foo", null, headers);
    Map<String, NewCookie> expectedCookies = ImmutableMap.of("name", new NewCookie("name", "andrew"),
                                                             "company", new NewCookie("company", "codenvy", "/path", "codenvy.com", 1, "comment", 300, null, true, true));

    assertEquals(expectedCookies, response.getCookies());
}
 
Example #29
Source File: RestResponse.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * @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()]);
}
 
Example #30
Source File: UserResource.java    From tastjava with MIT License 5 votes vote down vote up
@Path("/login")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response login() {
    String token = JWTProvider.createToken(1);
    NewCookie cookie = new NewCookie("jwt-authToken", token,"/", "", "comment", 3600, false);
    return Response.ok("OK").cookie(cookie).build();
}