Search in sources :

Example 16 with JSONObject

use of org.jose4j.json.internal.json_simple.JSONObject in project light-example-4j by networknt.

the class CreateTodoIT method testCreateTodo.

@Test
public void testCreateTodo() throws ClientException, ApiException {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("host", "lightapi.net");
    map.put("service", "todo");
    map.put("action", "create");
    map.put("version", "0.1.0");
    Map<String, Object> data = new HashMap<>();
    data.put("title", "create todo from hybrid service unit test");
    data.put("completed", false);
    data.put("order", 1);
    map.put("data", data);
    JSONObject json = new JSONObject();
    json.putAll(map);
    System.out.printf("JSON: %s", json.toString());
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/api/json").setMethod(Methods.POST);
        request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
        request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
        connection.sendRequest(request, client.createClientCallback(reference, latch, json.toString()));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) ApiException(com.networknt.exception.ApiException) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) ClientConnection(io.undertow.client.ClientConnection) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 17 with JSONObject

use of org.jose4j.json.internal.json_simple.JSONObject in project java by kubernetes-client.

the class OpenIDConnectAuthenticationTest method testRefreshSuccess.

@Test
public void testRefreshSuccess() throws Exception {
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(OIDC_KS_PATH), OIDC_KS_PASSWORD);
    String refreshedJWT = TestUtils.generateJWT("someuser", "https://localhost:" + PORT, (PrivateKey) ks.getKey("oidc-sig", OIDC_KS_PASSWORD), TestUtils.DateOptions.Now);
    stubFor(get("/.well-known/openid-configuration").willReturn(aResponse().withStatus(200).withBody("{\"issuer\":\"https://localhost:8043\",\"authorization_endpoint\":\"https://localhost:8043/auth\",\"token_endpoint\":\"https://localhost:8043/token\",\"userinfo_endpoint\":\"https://localhost:8043/userinfo\",\"revocation_endpoint\":\"https://localhost:8043/revoke\",\"jwks_uri\":\"https://localhost:8043/certs\",\"response_types_supported\":[\"code\",\"token\",\"id_token\",\"code token\",\"code id_token\",\"token id_token\",\"code token id_token\",\"none\"],\"subject_types_supported\":[\"public\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"scopes_supported\":[\"openid\",\"email\",\"profile\"],\"token_endpoint_auth_methods_supported\":[\"client_secret_post\"],\"claims_supported\":[\"sub\",\"aud\",\"iss\",\"exp\",\"sub\",\"name\",\"groups\",\"preferred_username\",\"email\"],\"code_challenge_methods_supported\":[\"plain\",\"S256\"]}")));
    JSONObject respToken = new JSONObject();
    respToken.put("id_token", refreshedJWT);
    respToken.put("refresh_token", "new_refresh_token");
    stubFor(post("/token").withBasicAuth("kubernetes", "").withRequestBody(matching("refresh_token=refresh-me-please&grant_type=refresh_token")).willReturn(aResponse().withStatus(200).withBody(respToken.toString())));
    OpenIDConnectAuthenticator oidcAuth = new OpenIDConnectAuthenticator();
    Map<String, Object> config = new HashMap<String, Object>();
    KeyStore serverKs = KeyStore.getInstance("JKS");
    serverKs.load(new FileInputStream(OIDC_SERVER_KS_PATH), OIDC_KS_PASSWORD);
    String jwt = TestUtils.generateJWT("someuser", "https://localhost:" + PORT, (PrivateKey) ks.getKey("oidc-sig", OIDC_KS_PASSWORD), TestUtils.DateOptions.Past);
    config.put(OpenIDConnectAuthenticator.OIDC_ID_TOKEN, jwt);
    config.put(OpenIDConnectAuthenticator.OIDC_ISSUER, "https://localhost:" + PORT);
    config.put(OpenIDConnectAuthenticator.OIDC_CLIENT_ID, "kubernetes");
    config.put(OpenIDConnectAuthenticator.OIDC_REFRESH_TOKEN, "refresh-me-please");
    config.put(OpenIDConnectAuthenticator.OIDC_IDP_CERT_DATA, Base64.encodeBase64String(exportCert((X509Certificate) serverKs.getCertificate("mykey")).getBytes(StandardCharsets.UTF_8)));
    Map<String, Object> respMap = oidcAuth.refresh(config);
    assertEquals(refreshedJWT, respMap.get(OpenIDConnectAuthenticator.OIDC_ID_TOKEN));
    assertEquals("new_refresh_token", respMap.get(OpenIDConnectAuthenticator.OIDC_REFRESH_TOKEN));
}
Also used : OpenIDConnectAuthenticator(io.kubernetes.client.util.authenticators.OpenIDConnectAuthenticator) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) HashMap(java.util.HashMap) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 18 with JSONObject

use of org.jose4j.json.internal.json_simple.JSONObject in project stdlib by petergeneric.

the class UserManagerOAuthServiceImpl method createOpenIDConnectUserInfo.

String createOpenIDConnectUserInfo(OAuthSessionEntity session) {
    try {
        JSONObject obj = new JSONObject();
        final UserEntity user = session.getContext().getUser();
        // Unique ID for this user
        obj.put("sub", user.getId());
        // Audience
        obj.put("client_id", session.getContext().getService().getId());
        // Issued At
        obj.put("iat", session.getCreated().getMillis() / 1000);
        // Expires
        obj.put("exp", session.getExpires().getMillis() / 1000);
        // Optional fields (N.B. technically per spec this info should be in a specifically requested scope)
        obj.put("name", user.getName());
        obj.put("email", user.getEmail());
        obj.put("zoneinfo", user.getTimeZone());
        obj.put("datetime_format", user.getDateFormat());
        List<String> roles = user.getRoles().stream().map(r -> r.getId()).collect(Collectors.toList());
        // Different clients use different key names here, so populate many claims with the same data
        obj.put("groups", roles);
        obj.put("roles", roles);
        obj.put("group", roles);
        obj.put("role", roles);
        return obj.toJSONString();
    } catch (JSONException e) {
        throw new RuntimeException("Unable to serialise OAuth2TokenResponse: " + e.getMessage(), e);
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Arrays(java.util.Arrays) TemplateCall(com.peterphi.std.guice.web.rest.templating.TemplateCall) OAuthSessionDaoImpl(com.peterphi.usermanager.db.dao.hibernate.OAuthSessionDaoImpl) Inject(com.google.inject.Inject) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) Templater(com.peterphi.std.guice.web.rest.templating.Templater) OAuth2TokenResponse(com.peterphi.usermanager.rest.iface.oauth2server.types.OAuth2TokenResponse) ArrayList(java.util.ArrayList) AuthConstraint(com.peterphi.std.guice.common.auth.annotations.AuthConstraint) UserEntity(com.peterphi.usermanager.db.entity.UserEntity) Logger(org.apache.log4j.Logger) CSRFTokenStore(com.peterphi.usermanager.guice.token.CSRFTokenStore) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) HttpCallContext(com.peterphi.std.guice.web.HttpCallContext) UserLogin(com.peterphi.usermanager.guice.authentication.UserLogin) OAuthServiceEntity(com.peterphi.usermanager.db.entity.OAuthServiceEntity) UserManagerBearerToken(com.peterphi.usermanager.util.UserManagerBearerToken) UserDaoImpl(com.peterphi.usermanager.db.dao.hibernate.UserDaoImpl) OAuthSessionEntity(com.peterphi.usermanager.db.entity.OAuthSessionEntity) UriBuilder(javax.ws.rs.core.UriBuilder) OAuthDelegatedTokenEntity(com.peterphi.usermanager.db.entity.OAuthDelegatedTokenEntity) URI(java.net.URI) Doc(com.peterphi.std.annotation.Doc) Period(org.joda.time.Period) Retry(com.peterphi.std.guice.common.retry.annotation.Retry) UserManagerUser(com.peterphi.usermanager.rest.type.UserManagerUser) DateTime(org.joda.time.DateTime) Transactional(com.peterphi.std.guice.database.annotation.Transactional) Set(java.util.Set) Collectors(java.util.stream.Collectors) BasicAuthHelper(org.jboss.resteasy.util.BasicAuthHelper) OAuthSessionContextDaoImpl(com.peterphi.usermanager.db.dao.hibernate.OAuthSessionContextDaoImpl) Provider(com.google.inject.Provider) List(java.util.List) UserMarshaller(com.peterphi.usermanager.rest.marshaller.UserMarshaller) OAuthSessionContextEntity(com.peterphi.usermanager.db.entity.OAuthSessionContextEntity) Response(javax.ws.rs.core.Response) RoleEntity(com.peterphi.usermanager.db.entity.RoleEntity) OAuthServiceDaoImpl(com.peterphi.usermanager.db.dao.hibernate.OAuthServiceDaoImpl) Named(com.google.inject.name.Named) CurrentUser(com.peterphi.std.guice.common.auth.iface.CurrentUser) UserManagerOAuthService(com.peterphi.usermanager.rest.iface.oauth2server.UserManagerOAuthService) CacheControl(javax.ws.rs.core.CacheControl) JSONException(org.eclipse.persistence.exceptions.JSONException) Collections(java.util.Collections) OAuthDelegatedTokenDaoImpl(com.peterphi.usermanager.db.dao.hibernate.OAuthDelegatedTokenDaoImpl) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) JSONException(org.eclipse.persistence.exceptions.JSONException) UserEntity(com.peterphi.usermanager.db.entity.UserEntity)

Example 19 with JSONObject

use of org.jose4j.json.internal.json_simple.JSONObject in project service-proxy by membrane.

the class GenericJsonParserTest method testCombined.

@Test
public void testCombined() {
    JSONObject spec = new JSONObject(new HashMap<String, Object>() {

        {
            put("port", 2020);
            put("blockRequest", true);
            put("path", new HashMap<String, Object>() {

                {
                    put("isRegExp", true);
                    put("value", "/foo");
                }
            });
            put("interceptors", Arrays.asList(new HashMap<String, Object>() {

                {
                    put("groovy", new HashMap<String, Object>() {

                        {
                            put("src", "println()");
                        }
                    });
                }
            }, new HashMap<String, Object>() {

                {
                    put("target", new HashMap<String, Object>() {

                        {
                            put("host", "localhost");
                            put("port", 8080);
                        }
                    });
                }
            }));
        }
    });
    ServiceProxy sp = GenericJsonParser.parse(ServiceProxy.class, spec);
    assertEquals(2020, sp.getPort());
    assertTrue(sp.isBlockRequest());
    assertTrue(sp.getPath().isRegExp());
    assertEquals("/foo", sp.getPath().getValue());
    assertEquals(2, sp.getInterceptors().size());
    assertTrue(sp.getInterceptors().get(0) instanceof GroovyInterceptor);
    assertEquals("println()", ((GroovyInterceptor) sp.getInterceptors().get(0)).getSrc());
    assertTrue(sp.getInterceptors().get(1) instanceof AbstractServiceProxy.Target);
    assertEquals("localhost", ((AbstractServiceProxy.Target) sp.getInterceptors().get(1)).getHost());
    assertEquals(8080, ((AbstractServiceProxy.Target) sp.getInterceptors().get(1)).getPort());
}
Also used : AbstractServiceProxy(com.predic8.membrane.core.rules.AbstractServiceProxy) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) AbstractServiceProxy(com.predic8.membrane.core.rules.AbstractServiceProxy) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) GroovyInterceptor(com.predic8.membrane.core.interceptor.groovy.GroovyInterceptor) HashMap(java.util.HashMap) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) Test(org.junit.Test)

Example 20 with JSONObject

use of org.jose4j.json.internal.json_simple.JSONObject in project service-proxy by membrane.

the class GenericJsonParserTest method testAttributeInteger.

@Test
public void testAttributeInteger() {
    int want = 3000;
    JSONObject spec = new JSONObject(new HashMap<String, Object>() {

        {
            put("port", want);
        }
    });
    ServiceProxy sp = GenericJsonParser.parse(ServiceProxy.class, spec);
    assertEquals(want, sp.getPort());
}
Also used : JSONObject(org.jose4j.json.internal.json_simple.JSONObject) AbstractServiceProxy(com.predic8.membrane.core.rules.AbstractServiceProxy) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) JSONObject(org.jose4j.json.internal.json_simple.JSONObject) Test(org.junit.Test)

Aggregations

JSONObject (org.jose4j.json.internal.json_simple.JSONObject)29 Test (org.junit.Test)14 HashMap (java.util.HashMap)12 Test (org.testng.annotations.Test)8 AbstractServiceProxy (com.predic8.membrane.core.rules.AbstractServiceProxy)7 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)7 URI (java.net.URI)6 InvalidUpdateDefinition (org.openecard.common.util.InvalidUpdateDefinition)6 Http2Client (com.networknt.client.Http2Client)5 ApiException (com.networknt.exception.ApiException)5 ClientException (com.networknt.exception.ClientException)5 ClientConnection (io.undertow.client.ClientConnection)5 ClientRequest (io.undertow.client.ClientRequest)5 ClientResponse (io.undertow.client.ClientResponse)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 URL (java.net.URL)4 GroovyInterceptor (com.predic8.membrane.core.interceptor.groovy.GroovyInterceptor)3 IOException (java.io.IOException)2 KeyStore (java.security.KeyStore)2