Java Code Examples for org.apache.cxf.jaxrs.client.WebClient#post()

The following examples show how to use org.apache.cxf.jaxrs.client.WebClient#post() . 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: STSRESTTest.java    From cxf with Apache License 2.0 7 votes vote down vote up
@org.junit.Test
public void testIssueSAML2TokenViaPOST() throws Exception {
    WebClient client = webClient()
        .type(MediaType.APPLICATION_XML)
        .accept(MediaType.APPLICATION_XML);

    // Create RequestSecurityToken
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", WST_NS_05_12);

    writer.writeStartElement("wst", "RequestType", WST_NS_05_12);
    writer.writeCharacters(WST_NS_05_12 + "/Issue");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", WST_NS_05_12);
    writer.writeCharacters(SAML2_TOKEN_TYPE);
    writer.writeEndElement();

    writer.writeEndElement();

    RequestSecurityTokenResponseType securityResponse = client.post(
        new DOMSource(writer.getDocument().getDocumentElement()),
        RequestSecurityTokenResponseType.class);

    validateSAMLSecurityTokenResponse(securityResponse, true);
}
 
Example 2
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testBadSignatureCertificateTest() throws Exception {

    URL busFile = JWTAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtincludecert/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jks");
    properties.put("rs.security.keystore.password", "password");
    properties.put("rs.security.key.password", "password");
    properties.put("rs.security.keystore.alias", "bethal");
    properties.put("rs.security.keystore.file", "keys/Bethal.jks");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put("rs.security.signature.include.cert", "true");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example 3
Source File: BatchRequest.java    From syncope with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the current request, with items accumulated by invoking methods on proxies obtained via
 * {@link #getService(java.lang.Class)}, to the Batch service, and awaits for a synchronous or asynchronous
 * response, depending on the {@code async} parameter.
 * It also clears out the accumulated items, in case of reuse of this instance for subsequent requests.
 *
 * @param async whether asynchronous Batch process is requested, or not
 * @return batch response
 */
public BatchResponse commit(final boolean async) {
    String boundary = "--batch_" + UUID.randomUUID().toString();

    WebClient webClient = WebClient.create(bcfb.getAddress()).path("batch").
            header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt).
            type(RESTHeaders.multipartMixedWith(boundary.substring(2)));
    if (async) {
        webClient.header(RESTHeaders.PREFER, Preference.RESPOND_ASYNC);
    }
    if (tlsClientParameters != null) {
        ClientConfiguration config = WebClient.getConfig(webClient);
        HTTPConduit httpConduit = (HTTPConduit) config.getConduit();
        httpConduit.setTlsClientParameters(tlsClientParameters);
    }

    String body = BatchPayloadGenerator.generate(bcfb.getBatchRequestItems(), boundary);
    LOG.debug("Batch request body:\n{}", body);

    initBatchClientFactoryBean();

    return new BatchResponse(boundary, jwt, tlsClientParameters, webClient.post(body));
}
 
Example 4
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpSignatureOutProperties() {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.out.properties",
                   "org/apache/cxf/systest/jaxrs/security/httpsignature/alice.httpsig.properties");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 5
Source File: IntrospectionServiceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testInvalidToken() throws Exception {
    URL busFile = IntrospectionServiceTest.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 Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client);
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());

    // Now query the token introspection service
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    client.accept("application/json").type("application/x-www-form-urlencoded");
    Form form = new Form();
    form.param("token", accessToken.getTokenKey() + "-xyz");
    client.path("introspect/");
    Response response = client.post(form);

    TokenIntrospection tokenIntrospection = response.readEntity(TokenIntrospection.class);
    assertFalse(tokenIntrospection.isActive());
}
 
Example 6
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncorrectDigestAlgorithm() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateDigestTestInterceptor signatureFilter = new CreateDigestTestInterceptor("SHA-1");

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner(keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(400, response.getStatus());
}
 
Example 7
Source File: JAXRSClientServerProxySpringBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookWithRequestScope() {
    // the BookStore method which will handle this request depends on the injected HttpHeaders
    WebClient wc = WebClient.create("http://localhost:" + PORT + "/test/request/bookstore/booksecho2");
    wc.type("text/plain").accept("text/plain");
    wc.header("CustomHeader", "custom-header");
    String value = wc.post("CXF", String.class);
    assertEquals("CXF", value);
    assertEquals("custom-header", wc.getResponse().getMetadata().getFirst("CustomHeader"));
}
 
Example 8
Source File: TokenCache.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
private ClientAccessToken getAccessToken() throws NoPrivateKeyException {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(config.getServiceAccountEmail());
    claims.setAudience(config.getServiceAccountTokenUri());
    claims.setSubject(config.getServiceAccountSubject());

    long issuedAt = OAuthUtils.getIssuedAt();
    long tokenTimeout = config.getServiceAccountTokenLifetime();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + tokenTimeout);
    String scopes = String.join(" ", config.getServiceAccountScopes());
    claims.setProperty("scope", scopes);

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(config.readServiceAccountKey());

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create(config.getServiceAccountTokenUri(),
            Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter()));

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example 9
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationNoRole() throws Exception {

    URL busFile = JWTAuthnAuthzTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtauthz/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example 10
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpSignatureResponseServiceProperties() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner(keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    VerifySignatureClientFilter signatureResponseFilter = new VerifySignatureClientFilter();
    MessageVerifier messageVerifier = new MessageVerifier(new CustomPublicKeyProvider());
    signatureResponseFilter.setMessageVerifier(messageVerifier);

    List<Object> providers = new ArrayList<>();
    providers.add(signatureFilter);
    providers.add(signatureResponseFilter);
    String address = "http://localhost:" + PORT + "/httpsigresponseprops/bookstore/books";
    WebClient client = WebClient.create(address, providers, busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 11
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpSignatureSignSpecificHeaderProperties() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.properties",
                   "org/apache/cxf/systest/jaxrs/security/httpsignature/alice.httpsig.properties");
    List<String> headerList = Arrays.asList("accept", "(request-target)");
    properties.put("rs.security.http.signature.out.headers", headerList);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 12
Source File: OIDCDynamicRegistrationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUpdateClient() throws Exception {
    URL busFile = OIDCDynamicRegistrationTest.class.getResource("client.xml");
    String address = "https://localhost:" + DYNREG_SERVER.getPort() + "/services/dynamicWithAt/register";
    WebClient wc =
        WebClient.create(address, Collections.singletonList(new JsonMapObjectProvider()), busFile.toString())
        .accept("application/json").type("application/json")
        .authorization(new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, ACCESS_TOKEN));

    final ClientRegistration reg = newClientRegistrationCodeGrant();
    final ClientRegistrationResponse clientRegistrationResponse = wc
        .post(reg, ClientRegistrationResponse.class);

    final String regAccessToken = clientRegistrationResponse.getRegistrationAccessToken();
    assertNotNull(regAccessToken);

    reg.setScope(OidcUtils.getEmailScope());
    final ClientRegistration updatedClientRegistration = wc.path(clientRegistrationResponse.getClientId())
        .authorization(new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, regAccessToken))
        .put(reg, ClientRegistration.class);

    assertEquals(OidcUtils.getEmailScope(), updatedClientRegistration.getScope());
    // https://tools.ietf.org/html/rfc7592#section-2.2
    assertNull(updatedClientRegistration.getProperty("registration_access_token"));
    assertNull(updatedClientRegistration.getProperty("registration_client_uri"));
    assertNull(updatedClientRegistration.getProperty("client_secret_expires_at"));
    assertNull(updatedClientRegistration.getProperty("client_id_issued_at"));

    wc.authorization(null);

    assertEquals(Status.UNAUTHORIZED.getStatusCode(),
        wc.put(reg).getStatus());
    assertEquals(Status.UNAUTHORIZED.getStatusCode(),
        wc.delete().getStatus());

    wc.authorization(new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, regAccessToken));
    assertEquals(200, wc.delete().getStatus());
}
 
Example 13
Source File: JweJwsAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedTokenFailure() throws Exception {

    URL busFile = JweJwsAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwsWriterInterceptor writerInterceptor = new JwsWriterInterceptor();
    writerInterceptor.setSignatureProvider(new NoneJwsSignatureProvider());
    providers.add(writerInterceptor);

    String address = "http://localhost:" + PORT + "/jws/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "none");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example 14
Source File: JAXRSSamlAuthorizationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostBookUserRole() throws Exception {
    String address = "https://localhost:" + PORT + "/saml-roles/bookstore/books";
    WebClient wc = createWebClient(address, null);
    wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);
    try {
        wc.post(new Book("CXF", 125L), Book.class);
        fail("403 is expected");
    } catch (WebApplicationException ex) {
        assertEquals(403, ex.getResponse().getStatus());
    }
}
 
Example 15
Source File: RestRequestTandem.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
private static void completeTaskUseForm(String taskId, String taskName, List<Map<String, String>> properties) throws IOException {
    WebClient client = createClient("form/form-data");
    // 非常重要
    client.type("application/json;charset=UTF-8");
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("taskId", taskId);
    if (properties != null) {
        parameters.put("properties", properties);
    }

    String body = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parameters);
    printJsonString("完成任务-Form[" + taskId + "-" + taskName + "]", body);
    Response response = client.post(body);
    printResult("完成任务-Form[" + taskId + "-" + taskName + "]", response);
}
 
Example 16
Source File: OAuth2FiltersTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testServiceWithTokenUsingIncorrectAudience() throws Exception {
    // Get Authorization Code
    String oauthService = "https://localhost:" + OAUTH_PORT + "/services/";

    WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(),
                                             "alice", "security", null);
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, null, "consumer-id-aud2");
    assertNotNull(code);

    // Now get the access token
    oauthClient = WebClient.create(oauthService, "consumer-id-aud2", "this-is-a-secret", null);

    String address = "https://localhost:" + PORT + "/securedxyz/bookstore/books";
    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code,
                                                            "consumer-id-aud2", address);
    assertNotNull(accessToken.getTokenKey());

    // Now invoke on the service with the access token
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders())
        .authorization(new ClientAccessToken(BEARER_AUTHORIZATION_SCHEME, accessToken.getTokenKey()));

    Response response = client.post(new Book("book", 123L));
    assertEquals(Family.CLIENT_ERROR, response.getStatusInfo().getFamily());
}
 
Example 17
Source File: EnvironmentWebClient.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public void excludeContainerFromEnvironment( final String environmentId, final String containerId )
        throws PeerException
{
    WebClient client = null;
    Response response;
    try
    {
        remotePeer.checkRelation();
        String path = String.format( "/%s/containers/%s/exclude", environmentId, containerId );
        client = WebClientBuilder.buildEnvironmentWebClient( peerInfo, path, provider );

        client.type( MediaType.APPLICATION_JSON );
        client.accept( MediaType.APPLICATION_JSON );
        response = client.post( null );
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage(), e );
        throw new PeerException( "Error excluding container from environment: " + e.getMessage() );
    }
    finally
    {
        WebClientBuilder.close( client );
    }

    WebClientBuilder.checkResponse( response );
}
 
Example 18
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testUserInfoRefreshToken() throws Exception {
    URL busFile = UserInfoTest.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 Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    String oldAccessToken = accessToken.getTokenKey();
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);

    // Refresh the access token
    client.type("application/x-www-form-urlencoded").accept("application/json");

    Form form = new Form();
    form.param("grant_type", "refresh_token");
    form.param("refresh_token", accessToken.getRefreshToken());
    form.param("client_id", "consumer-id");
    form.param("scope", "openid");
    Response response = client.post(form);

    accessToken = response.readEntity(ClientAccessToken.class);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());
    accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    String newAccessToken = accessToken.getTokenKey();

    // Now test the UserInfoService.

    // The old Access Token should fail
    String userInfoAddress = "https://localhost:" + port + "/ui/plain/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/json");
    userInfoClient.header("Authorization", "Bearer " + oldAccessToken);

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 401);

    // The refreshed Access Token should work
    userInfoClient.replaceHeader("Authorization", "Bearer " + newAccessToken);
    serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    UserInfo userInfo = serviceResponse.readEntity(UserInfo.class);
    assertNotNull(userInfo);

    assertEquals("alice", userInfo.getSubject());
    assertEquals("consumer-id", userInfo.getAudience());
}
 
Example 19
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testEncryptionDynamic() throws Exception {

    URL busFile = JWTAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwtAuthenticationClientFilter clientFilter = new JwtAuthenticationClientFilter();
    clientFilter.setJwsRequired(false);
    clientFilter.setJweRequired(true);
    providers.add(clientFilter);

    String address = "https://localhost:" + PORT + "/encryptedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A128GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA-OAEP");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
 
Example 20
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testJWTUnauthenticatedSignature() throws Exception {
    URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Create the JWT Token
    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("consumer-id");
    claims.setIssuer("DoubleItSTSIssuer");
    Instant now = Instant.now();
    claims.setIssuedAt(now.getEpochSecond());
    claims.setExpiryTime(now.plusSeconds(60L).getEpochSecond());
    String audience = "https://localhost:" + port + "/services/token";
    claims.setAudiences(Collections.singletonList(audience));

    // Sign the JWT Token
    Properties signingProperties = new Properties();
    signingProperties.put("rs.security.keystore.type", "jks");
    signingProperties.put("rs.security.keystore.password", "security");
    signingProperties.put("rs.security.keystore.alias", "smallkey");
    signingProperties.put("rs.security.keystore.file",
        "org/apache/cxf/systest/jaxrs/security/certs/smallkeysize.jks");
    signingProperties.put("rs.security.key.password", "security");
    signingProperties.put("rs.security.signature.algorithm", "RS256");

    JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);

    JwsSignatureProvider sigProvider =
        JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);

    String token = jws.signWith(sigProvider);

    // Get Access Token
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    form.param("assertion", token);
    form.param("client_id", "consumer-id");
    Response response = client.post(form);

    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on an unauthenticated token");
    } catch (Exception ex) {
        // expected
    }
}