Java Code Examples for javax.ws.rs.core.Response#getHeaderString()

The following examples show how to use javax.ws.rs.core.Response#getHeaderString() . 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: HttpDPMAuth.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public String login() {
  Response response = null;
  try {
    Map<String, String> loginJson = new HashMap<>();
    loginJson.put("userName", this.username);
    loginJson.put("password", this.password);
    response = ClientBuilder.newClient()
        .target(dpmBaseURL + "/security/public-rest/v1/authentication/login")
        .register(new CsrfProtectionFilter("CSRF"))
        .request()
        .post(Entity.json(loginJson));
    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
      throw new RuntimeException("DPM Login failed, status code '" +
          response.getStatus() + "': " +
          response.readEntity(String.class)
      );
    }

    return response.getHeaderString(X_USER_AUTH_TOKEN);
  } finally {
    if (response != null) {
      response.close();
    }
  }
}
 
Example 2
Source File: JWTITCase.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void queryUsingToken() throws ParseException {
    // Get the token
    SyncopeClient localClient = clientFactory.create(ADMIN_UNAME, ADMIN_PWD);
    AccessTokenService accessTokenService = localClient.getService(AccessTokenService.class);

    Response response = accessTokenService.login();
    String token = response.getHeaderString(RESTHeaders.TOKEN);
    assertNotNull(token);

    // Query the UserSelfService using the token
    SyncopeClient jwtClient = clientFactory.create(token);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    jwtUserSelfService.read();

    // Test a "bad" token
    jwtClient = clientFactory.create(token + "xyz");
    jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on a modified token");
    } catch (WebServiceException ex) {
        // expected
    }
}
 
Example 3
Source File: PushEndpointTest.java    From divide with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnregister() throws Exception {
    Credentials user = AuthenticationEndpointTest.signUpUser(this);
    PublicKey key = AuthenticationEndpointTest.getPublicKey(this);

    Response tokenResponse =  registerToken(user, key, this);

    String newAuthToken = tokenResponse.getHeaderString("Authorization");

    Response response = target("/push")
            .request()
            .header(ContainerRequest.AUTHORIZATION, "CUSTOM " + newAuthToken)
            .delete();
    int statusCode = response.getStatus();
    assertEquals(200,statusCode);
    Collection<TransientObject> list = container.serverDao.get(Query.safeTable(Credentials.class),user.getObjectKey());
    TransientObject o = ObjectUtils.get1stOrNull(list);
    user = TestUtils.convert(o,Credentials.class);
    assertNotNull(user);
    assertEquals("", user.getPushMessagingKey()); // check the token was actually saved
}
 
Example 4
Source File: ApiHandler.java    From riotapi with Apache License 2.0 6 votes vote down vote up
/**
 * Open the request to the web target and returns an InputStreamReader for the message body
 *
 * @param target the web target to access
 * @return the reader for the message body
 */
@SneakyThrows(IOException.class)
private InputStreamReader $(WebTarget target) {

    Response response = target.request().accept(MediaType.APPLICATION_JSON_TYPE).acceptEncoding("gzip").get();
    if (response.getStatus() != 200) {
        throw new RequestException(response.getStatus(), RequestException.ErrorType.getByCode(response.getStatus()));
    }

    String encoding = response.getHeaderString("Content-Encoding");
    if (encoding != null && encoding.equals("gzip")) {
        return new InputStreamReader(new GZIPInputStream((java.io.InputStream) response.getEntity()));
    } else {
        return new InputStreamReader((java.io.InputStream) response.getEntity());
    }
}
 
Example 5
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testRefreshImplicitGrant() throws Exception {
    URL busFile = AuthorizationGrantTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Access Token
    client.type("application/json").accept("application/json");
    client.query("client_id", "consumer-id");
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("response_type", "token");
    client.path("authorize-implicit/");
    Response response = client.get();

    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);

    // Now call "decision" to get the access token
    client.path("decision");
    client.type("application/x-www-form-urlencoded");

    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    form.param("oauthDecision", "allow");

    response = client.post(form);

    String location = response.getHeaderString("Location");
    String accessToken = OAuth2TestUtils.getSubstring(location, "access_token");
    assertNotNull(accessToken);
    assertFalse(location.contains("refresh"));
}
 
Example 6
Source File: NotificationClient.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch all notifications for a given username. This method will paginate through all of the
 * available notifications for a user.
 *
 * @param username User to fetch notifications
 * @return Sorted set of all notifications for the user
 */
public Optional<SortedSet<Notification>> fetch(final String username) {

  final URI uri = getTarget(username);
  final ImmutableSortedSet.Builder<Notification> results = ImmutableSortedSet.naturalOrder();
  String nextRange = null;
  boolean paginate = true;

  try (Timer.Context context = fetchTimer.time()) {
    while (paginate) {
      LOGGER.info("GET {}", uri);

      final Invocation.Builder builder = client.target(uri).request(APPLICATION_JSON);
      if (nextRange != null) {
        builder.header("Range", nextRange);
      }

      final Response response = builder.get();
      nextRange = response.getHeaderString("Next-Range");
      if (nextRange == null) {
        paginate = false;
      }

      if (response.getStatus() == Response.Status.OK.getStatusCode()
          || response.getStatus() == Response.Status.PARTIAL_CONTENT.getStatusCode()) {
        results.addAll(response.readEntity(new GenericType<List<Notification>>() {}));
      }
      response.close();
    }
    return Optional.of(results.build());

  } catch (Exception e) {
    LOGGER.warn("Unable to fetch notification for {}", username, e);
  }
  return Optional.empty();
}
 
Example 7
Source File: AbstractRESTDataProvider.java    From quandl4j with Apache License 2.0 5 votes vote down vote up
private Long parseOptionalHeader(final Response response, final String field) {
  String value = response.getHeaderString(field);
  if (value != null) {
    try {
      return Long.valueOf(value);
    } catch (NumberFormatException nfe) {
    }
  }
  return null;
}
 
Example 8
Source File: Pager.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
/**
 * Get the specified integer header value from the Response instance.
 *
 * @param response the Response instance to get the value from
 * @param key      the HTTP header key to get the value for
 * @return the specified integer header value from the Response instance
 * @throws GitLabApiException if any error occurs
 */
private int getHeaderValue(Response response, String key) throws GitLabApiException {

    String value = response.getHeaderString(key);
    value = (value != null ? value.trim() : null);
    if (value == null || value.length() == 0)
        throw new GitLabApiException("Missing '" + key + "' header from server");

    try {
        return (Integer.parseInt(value));
    } catch (NumberFormatException nfe) {
        throw new GitLabApiException("Invalid '" + key + "' header value (" + value + ") from server");
    }
}
 
Example 9
Source File: AsyncMethodTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
/**
     * Tests that a Rest Client interface method that returns CompletionStage
     * is invoked asychronously - checking that the thread ID of the response
     * does not match the thread ID of the calling thread.
     *
     * @throws Exception - indicates test failure
     */
    // Commented out for now. May revisit in future an alternative way to test asynchronous handling.
//    @Test
    public void testInterfaceMethodWithCompletionStageResponseReturnIsInvokedAsynchronously() throws Exception{
        final String expectedBody = "Hello, Async Client!";
        stubFor(get(urlEqualTo("/"))
            .willReturn(aResponse()
                .withBody(expectedBody)));

        final String mainThreadId = "" + Thread.currentThread().getId();

        SimpleGetApiAsync api = RestClientBuilder.newBuilder()
            .baseUrl(getServerURL())
            .register(ThreadedClientResponseFilter.class)
            .build(SimpleGetApiAsync.class);
        CompletionStage<Response> future = api.executeGet();

        Response response = future.toCompletableFuture().get();
        String body = response.readEntity(String.class);

        response.close();

        String responseThreadId = response.getHeaderString(ThreadedClientResponseFilter.RESPONSE_THREAD_ID_HEADER);
        assertNotNull(responseThreadId);
        assertNotEquals(responseThreadId, mainThreadId);
        assertEquals(body, expectedBody);

        verify(1, getRequestedFor(urlEqualTo("/")));
    }
 
Example 10
Source File: CommentsResourceIT.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
@Test
public void setup() {
    JsonObject comment = Json.createObjectBuilder()
            .add("text", "Who can fix this?")
            .add("byUser", 1L)
            .build();
    Response initiallyCreated = this.targetAPI
            .resolveTemplate("issueid", 1L)
            .request(MediaType.APPLICATION_JSON)
            .post(Entity.json(comment));
    assertThat(initiallyCreated.getStatus(), is(201));
    String location = initiallyCreated.getHeaderString("Location");
    assertNotNull(location);
    
    Response evenCreated = this.client.target(location).
            request(MediaType.APPLICATION_JSON).
            get();
    assertThat(evenCreated.getStatus(), is(200));
    
    comment = Json.createObjectBuilder()
            .add("text", "I can fix this")
            .add("byUser", 2L)
            .build();
    
    initiallyCreated = this.targetAPI
            .resolveTemplate("issueid", 1L)
            .request(MediaType.APPLICATION_JSON)
            .post(Entity.json(comment));
    location = initiallyCreated.getHeaderString("Location");
    assertNotNull(location);
    
    evenCreated = this.client.target(location).
            request(MediaType.APPLICATION_JSON).
            get();
    assertThat(evenCreated.getStatus(), is(200));       
    
}
 
Example 11
Source File: ODataExceptionMapperImplTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void dollarFormatXml() throws Exception {
  MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<String, String>();
  queryParameters.putSingle("$format", "xml");
  when(exceptionMapper.uriInfo.getQueryParameters()).thenReturn(queryParameters);

  Response response = exceptionMapper.toResponse(new Exception("text"));
  assertNotNull(response);
  String contentTypeHeader = response.getHeaderString(org.apache.olingo.odata2.api.commons.HttpHeaders.CONTENT_TYPE);
  assertEquals("application/xml", contentTypeHeader);
  String errorMessage = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertXpathExists("/a:error/a:code", errorMessage);
  assertXpathEvaluatesTo("text", "/a:error/a:message", errorMessage);
}
 
Example 12
Source File: ImportOperationTest.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Test(groups = { TEST_GROUP_NAME })
public void testImport() throws Exception {
    if (ON) {
        String path = BASE_VALID_URL;
        String inputFormat = FORMAT;
        String inputSource = "https://localhost:9443/source-fhir-server";
        String resourceType = "Patient";
        // https://s3.us-east.cloud-object-storage.appdomain.cloud/fhir-integration-test/test-import.ndjson
        String url = "test-import.ndjson";

        Response response = doPost(path, inputFormat, inputSource, resourceType, url);
        assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());

        // check the content-location that's returned.
        String contentLocation = response.getHeaderString("Content-Location");
        if (DEBUG) {
            System.out.println("Content Location: " + contentLocation);
        }

        assertTrue(contentLocation.contains(BASE_VALID_STATUS_URL));

        // Check eventual value
        response = polling(contentLocation);
        assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
    } else {
        System.out.println("Import Test Disabled, Skipping");
    }
}
 
Example 13
Source File: ODataExceptionMapperImplTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void dollarFormatUnknown() throws Exception {
  MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<String, String>();
  queryParameters.putSingle("$format", "someFormat");
  when(exceptionMapper.uriInfo.getQueryParameters()).thenReturn(queryParameters);

  Response response = exceptionMapper.toResponse(new Exception("text"));
  assertNotNull(response);
  String contentTypeHeader = response.getHeaderString(org.apache.olingo.odata2.api.commons.HttpHeaders.CONTENT_TYPE);
  assertEquals("application/xml", contentTypeHeader);
  String errorMessage = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertXpathExists("/a:error/a:code", errorMessage);
  assertXpathEvaluatesTo("text", "/a:error/a:message", errorMessage);
}
 
Example 14
Source File: GoogleMfaAuthTokenITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void deleteByToken() {
    GoogleMfaAuthToken token = createGoogleMfaAuthToken();
    Response response = googleMfaAuthTokenService.save(token);
    String key = response.getHeaderString(RESTHeaders.RESOURCE_KEY);
    assertNotNull(key);
    response = googleMfaAuthTokenService.deleteToken(token.getToken());
    assertEquals(response.getStatusInfo().getStatusCode(), Response.Status.NO_CONTENT.getStatusCode());
    assertTrue(googleMfaAuthTokenService.findTokensFor(token.getOwner()).getResult().isEmpty());
}
 
Example 15
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testImplicitFlowNoATHash() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Access Token
    client.type("application/json").accept("application/json");
    client.query("client_id", "consumer-id");
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("scope", "openid");
    client.query("response_type", "id_token");
    client.query("nonce", "1234565635");
    client.query("max_age", "300");
    client.path("authorize-implicit/");
    Response response = client.get();

    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);

    // Now call "decision" to get the access token
    client.path("decision");
    client.type("application/x-www-form-urlencoded");

    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    form.param("scope", authzData.getProposedScope());
    if (authzData.getResponseType() != null) {
        form.param("response_type", authzData.getResponseType());
    }
    if (authzData.getNonce() != null) {
        form.param("nonce", authzData.getNonce());
    }
    form.param("oauthDecision", "allow");

    response = client.post(form);

    String location = response.getHeaderString("Location");

    // Check IdToken
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
}
 
Example 16
Source File: AsyncMethodTest.java    From microprofile-rest-client with Apache License 2.0 4 votes vote down vote up
/**
 * This test uses a <code>ClientRequestFilter</code> to update the
 * destination URI.  It attempts to update it based on a ThreadLocal object
 * on the calling thread.  It uses an
 * <code>AsyncInvocationInterceptorFactory</code> provider to copy the
 * ThreadLocal value from the calling thread to the async thread.
 *
 * @throws Exception - indicates test failure
 */
@Test
public void testAsyncInvocationInterceptorProvider() throws Exception{
    final String expectedBody = "Hello, Async Intercepted Client!!";
    final Integer threadLocalInt = 808;
    final long mainThreadId = Thread.currentThread().getId();

    stubFor(get(urlEqualTo("/" + threadLocalInt))
            .willReturn(aResponse()
                    .withBody(expectedBody)));

    AtomicBoolean isThreadLocalCleared = new AtomicBoolean(true);
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(new Runnable(){
                @Override
                public void run() {
                    isThreadLocalCleared.set(TLAsyncInvocationInterceptorFactory.getTlInt() == 0);
                    r.run();
                }
            });
        }
    };
    ExecutorService testExecutorService = Executors.newSingleThreadExecutor(threadFactory);

    final TLAsyncInvocationInterceptorFactory aiiFactory = new TLAsyncInvocationInterceptorFactory(threadLocalInt);
    final TLClientResponseFilter responseFilter = new TLClientResponseFilter();
    SimpleGetApiAsync api = RestClientBuilder.newBuilder()
        .baseUrl(getServerURL())
        .register(TLAddPathClientRequestFilter.class)
        .register(aiiFactory)
        .register(responseFilter)
        .executorService(testExecutorService)
        .build(SimpleGetApiAsync.class);
    CompletionStage<Response> future = api.executeGet();

    Response response = future.toCompletableFuture().get();
    assertEquals(response.getStatus(), 200);
    String sentUri = response.getHeaderString("Sent-URI");
    assertTrue(sentUri.endsWith("/" + threadLocalInt));
    assertEquals((long) TLAsyncInvocationInterceptorFactory.getTlInt(), 808L);
    assertEquals((long) responseFilter.getThreadLocalIntDuringResponse(), (long) threadLocalInt);

    String body = response.readEntity(String.class);

    response.close();

    // force the test to wait for async thread to be recycled and re-used
    // and verify that the thread locals have been cleared.
    Future<?> f = testExecutorService.submit(new Runnable(){
        @Override
        public void run() {
            System.out.println("Reusing single thread pool thread");
        }
    });
    f.get(30, TimeUnit.SECONDS);
    assertTrue(isThreadLocalCleared.get());
    assertEquals(body, expectedBody);
    Map<String,Object> data = aiiFactory.getData();
    assertEquals(data.get("preThreadId"), mainThreadId);
    assertNotEquals(data.get("postThreadId"), mainThreadId);
    assertEquals(data.get("removeThreadId"), data.get("postThreadId"));
    assertEquals(data.get("AsyncThreadLocalPre"), 808);
    assertEquals(data.get("AsyncThreadLocalPost"), 0);

    verify(1, getRequestedFor(urlEqualTo("/" + threadLocalInt)));
}
 
Example 17
Source File: UserResourceTest.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
/** Tests the create user function. */
@Test
public void testCreateUser() throws Exception {
  // Test1: Add user.
  String loginAuthHeader =
      "Bearer "
          + new JWTVerifier()
              .createJWT("unauthenticated", new HashSet<String>(Arrays.asList("login")));
  User user1 =
      new User(
          null, "Isaac", "Newton", "inewton", "@inewton", "inewtonWishListLink", "mypassword");
  Response response = processRequest(userServiceURL, "POST", user1.getJson(), loginAuthHeader);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());
  String authHeader = response.getHeaderString("Authorization");
  new JWTVerifier().validateJWT(authHeader);

  JsonObject responseJson = toJsonObj(response.readEntity(String.class));
  String dbId = responseJson.getString(KEY_USER_ID);
  user1.setId(dbId);

  // Validate user.
  BasicDBObject dbUser =
      (BasicDBObject) database.getCollection("users").findOne(new ObjectId(dbId));
  assertTrue("User inewton was NOT found in database.", dbUser != null);
  assertTrue("User inewton does not contain expected data.", user1.isEqual(dbUser));

  // Test2: Try adding another user with the same userName.  This should fail.
  User user2 =
      new User(
          null,
          "Ivan",
          "Newton",
          "inewton",
          "@ivannewton",
          "ivannewtonWishListLink",
          "myPassword");
  response = processRequest(userServiceURL, "POST", user2.getJson(), loginAuthHeader);
  assertEquals(
      "HTTP response code should have been " + Status.BAD_REQUEST.getStatusCode() + ".",
      Status.BAD_REQUEST.getStatusCode(),
      response.getStatus());
}
 
Example 18
Source File: JWTITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void notBefore() throws ParseException {
    // Get an initial token
    SyncopeClient localClient = clientFactory.create(ADMIN_UNAME, ADMIN_PWD);
    AccessTokenService accessTokenService = localClient.getService(AccessTokenService.class);

    Response response = accessTokenService.login();
    String token = response.getHeaderString(RESTHeaders.TOKEN);
    assertNotNull(token);
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(token);
    String tokenId = consumer.getJwtClaims().getTokenId();

    // Create a new token using the Id of the first token
    Date now = new Date();
    long currentTime = now.getTime() / 1000L;

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(now);
    expiry.add(Calendar.MINUTE, 5);

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(ADMIN_UNAME);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(JWT_ISSUER);
    jwtClaims.setExpiryTime(expiry.getTime().getTime() / 1000L);
    jwtClaims.setNotBefore(currentTime + 60L);

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, JWS_ALGORITHM);
    JwtToken jwtToken = new JwtToken(jwsHeaders, jwtClaims);
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(jwtToken);

    String signed = producer.signWith(jwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on a token that is not valid yet");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 19
Source File: JWTITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void expiredToken() throws ParseException {
    // Get an initial token
    SyncopeClient localClient = clientFactory.create(ADMIN_UNAME, ADMIN_PWD);
    AccessTokenService accessTokenService = localClient.getService(AccessTokenService.class);

    Response response = accessTokenService.login();
    String token = response.getHeaderString(RESTHeaders.TOKEN);
    assertNotNull(token);
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(token);
    String tokenId = consumer.getJwtClaims().getTokenId();

    // Create a new token using the Id of the first token
    Date now = new Date();
    long currentTime = now.getTime() / 1000L;

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(now);
    expiry.add(Calendar.MINUTE, 5);

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(ADMIN_UNAME);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(JWT_ISSUER);
    jwtClaims.setExpiryTime((now.getTime() - 5000L) / 1000L);
    jwtClaims.setNotBefore(currentTime);

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, JWS_ALGORITHM);
    JwtToken jwtToken = new JwtToken(jwsHeaders, jwtClaims);
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(jwtToken);

    String signed = producer.signWith(jwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on an expired token");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 20
Source File: LoginResourceTest.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
/** Tests login with the wrong password. */
@Test
public void testLoginWrongPassword() throws Exception {
  // Add a user.
  String loginAuthHeader =
      "Bearer "
          + new JWTVerifier()
              .createJWT("unauthenticated", new HashSet<String>(Arrays.asList("login")));
  User user =
      new User(null, "Niels", "Bohr", "nBohr", "@nBohr", "nBohrWishListLink", "myPassword");
  Response response = processRequest(userServiceURL, "POST", user.getJson(), loginAuthHeader);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());
  String authHeader = response.getHeaderString("Authorization");
  new JWTVerifier().validateJWT(authHeader);

  JsonObject responseJson = toJsonObj(response.readEntity(String.class));
  String dbId = responseJson.getString(User.JSON_KEY_USER_ID);
  user.setId(dbId);

  // Find user in the database.
  BasicDBObject dbUser =
      (BasicDBObject) database.getCollection("users").findOne(new ObjectId(dbId));
  assertTrue("User rFeynman was NOT found in database.", dbUser != null);
  assertTrue("User rFeynman does not contain expected data.", user.isEqual(dbUser));

  // Test 1: Login the user with an incorrect password.  This should fail.
  JsonObjectBuilder loginPayload = Json.createObjectBuilder();
  loginPayload.add(User.JSON_KEY_USER_NAME, user.userName);
  loginPayload.add(User.JSON_KEY_USER_PASSWORD, user.password + "X");

  response =
      processRequest(
          userServiceLoginURL, "POST", loginPayload.build().toString(), loginAuthHeader);
  assertEquals(
      "HTTP response code should have been " + Status.UNAUTHORIZED.getStatusCode() + ".",
      Status.UNAUTHORIZED.getStatusCode(),
      response.getStatus());
}