Search in sources :

Example 81 with JSONArray

use of org.codehaus.jettison.json.JSONArray in project oxAuth by GluuFederation.

the class ClientInfoClient method _exec.

/**
     * Executes the call to the REST Service and processes the response.
     *
     * @return The service response.
     */
private ClientInfoResponse _exec() {
    // Prepare request parameters
    clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    clientRequest.setHttpMethod(getHttpMethod());
    if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD) {
        if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            clientRequest.header("Authorization", "Bearer " + getRequest().getAccessToken());
        }
    } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
        if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            clientRequest.formParameter("access_token", getRequest().getAccessToken());
        }
    } else if (getRequest().getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
        if (StringUtils.isNotBlank(getRequest().getAccessToken())) {
            clientRequest.queryParameter("access_token", getRequest().getAccessToken());
        }
    }
    // Call REST Service and handle response
    try {
        if (getRequest().getAuthorizationMethod() == null || getRequest().getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD || getRequest().getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER) {
            clientResponse = clientRequest.post(String.class);
        } else {
            //AuthorizationMethod.URL_QUERY_PARAMETER
            clientResponse = clientRequest.get(String.class);
        }
        int status = clientResponse.getStatus();
        setResponse(new ClientInfoResponse(status));
        String entity = clientResponse.getEntity(String.class);
        getResponse().setEntity(entity);
        getResponse().setHeaders(clientResponse.getMetadata());
        if (StringUtils.isNotBlank(entity)) {
            try {
                JSONObject jsonObj = new JSONObject(entity);
                if (jsonObj.has("error")) {
                    getResponse().setErrorType(UserInfoErrorResponseType.fromString(jsonObj.getString("error")));
                    jsonObj.remove("error");
                }
                if (jsonObj.has("error_description")) {
                    getResponse().setErrorDescription(jsonObj.getString("error_description"));
                    jsonObj.remove("error_description");
                }
                if (jsonObj.has("error_uri")) {
                    getResponse().setErrorUri(jsonObj.getString("error_uri"));
                    jsonObj.remove("error_uri");
                }
                for (Iterator<String> iterator = jsonObj.keys(); iterator.hasNext(); ) {
                    String key = iterator.next();
                    List<String> values = new ArrayList<String>();
                    JSONArray jsonArray = jsonObj.optJSONArray(key);
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String value = jsonArray.optString(i);
                            if (value != null) {
                                values.add(value);
                            }
                        }
                    } else {
                        String value = jsonObj.optString(key);
                        if (value != null) {
                            values.add(value);
                        }
                    }
                    getResponse().getClaims().put(key, values);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        closeConnection();
    }
    return getResponse();
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) JSONException(org.codehaus.jettison.json.JSONException)

Example 82 with JSONArray

use of org.codehaus.jettison.json.JSONArray in project oxAuth by GluuFederation.

the class OpenIdConnectDiscoveryClient method _exec2.

private OpenIdConnectDiscoveryResponse _exec2() {
    // Prepare request parameters
    clientRequest.accept(MEDIA_TYPE);
    clientRequest.setHttpMethod(getHttpMethod());
    if (StringUtils.isNotBlank(getRequest().getResource())) {
        clientRequest.queryParameter(RESOURCE, getRequest().getResource());
    }
    clientRequest.queryParameter(REL, REL_VALUE);
    // Call REST Service and handle response
    ClientResponse<String> clientResponse1;
    try {
        clientResponse1 = clientRequest.get(String.class);
        int status = clientResponse1.getStatus();
        setResponse(new OpenIdConnectDiscoveryResponse(status));
        String entity = clientResponse1.getEntity(String.class);
        getResponse().setEntity(entity);
        getResponse().setHeaders(clientResponse1.getMetadata());
        if (StringUtils.isNotBlank(entity)) {
            JSONObject jsonObj = new JSONObject(entity);
            getResponse().setSubject(jsonObj.getString(SUBJECT));
            JSONArray linksJsonArray = jsonObj.getJSONArray(LINKS);
            for (int i = 0; i < linksJsonArray.length(); i++) {
                WebFingerLink webFingerLink = new WebFingerLink();
                webFingerLink.setRel(linksJsonArray.getJSONObject(i).getString(REL));
                webFingerLink.setHref(linksJsonArray.getJSONObject(i).getString(HREF));
                getResponse().getLinks().add(webFingerLink);
            }
        }
    } catch (JSONException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return getResponse();
}
Also used : WebFingerLink(org.xdi.oxauth.model.discovery.WebFingerLink) JSONObject(org.codehaus.jettison.json.JSONObject) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) URISyntaxException(java.net.URISyntaxException) JSONException(org.codehaus.jettison.json.JSONException)

Example 83 with JSONArray

use of org.codehaus.jettison.json.JSONArray in project oxAuth by GluuFederation.

the class RegistrationRestWebServiceHttpTest method requestClientAssociate2.

@Parameters({ "redirectUris", "sectorIdentifierUri", "logoutUri" })
@Test
public void requestClientAssociate2(final String redirectUris, final String sectorIdentifierUri, final String logoutUri) throws Exception {
    showTitle("requestClientAssociate2");
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setContacts(Arrays.asList("javier@gluu.org", "javier.rojas.blum@gmail.com"));
    registerRequest.setScopes(Arrays.asList("openid", "address", "profile", "email", "phone", "clientinfo", "invalid_scope"));
    registerRequest.setLogoUri("http://www.gluu.org/wp-content/themes/gluursn/images/logo.png");
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    registerRequest.setPolicyUri("http://www.gluu.org/policy");
    registerRequest.setJwksUri("http://www.gluu.org/jwks");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
    registerRequest.setSubjectType(SubjectType.PAIRWISE);
    registerRequest.setRequestUris(Arrays.asList("http://www.gluu.org/request"));
    registerRequest.setFrontChannelLogoutUris(Lists.newArrayList(logoutUri));
    registerRequest.setFrontChannelLogoutSessionRequired(true);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.RS512);
    registerRequest.setIdTokenEncryptedResponseAlg(KeyEncryptionAlgorithm.RSA1_5);
    registerRequest.setIdTokenEncryptedResponseEnc(BlockEncryptionAlgorithm.A128CBC_PLUS_HS256);
    registerRequest.setUserInfoSignedResponseAlg(SignatureAlgorithm.RS384);
    registerRequest.setUserInfoEncryptedResponseAlg(KeyEncryptionAlgorithm.A128KW);
    registerRequest.setUserInfoEncryptedResponseEnc(BlockEncryptionAlgorithm.A128GCM);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
    registerRequest.setRequestObjectEncryptionAlg(KeyEncryptionAlgorithm.A256KW);
    registerRequest.setRequestObjectEncryptionEnc(BlockEncryptionAlgorithm.A256CBC_PLUS_HS512);
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    registerRequest.setTokenEndpointAuthSigningAlg(SignatureAlgorithm.ES256);
    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    registerClient.setExecutor(clientExecutor(true));
    RegisterResponse response = registerClient.exec();
    showClient(registerClient);
    assertEquals(response.getStatus(), 200, "Unexpected response code: " + response.getEntity());
    assertNotNull(response.getClientId());
    assertNotNull(response.getClientSecret());
    assertNotNull(response.getRegistrationAccessToken());
    assertNotNull(response.getClientSecretExpiresAt());
    assertNotNull(response.getClaims().get(SCOPES.toString()));
    assertNotNull(response.getClaims().get(FRONT_CHANNEL_LOGOUT_SESSION_REQUIRED.toString()));
    assertTrue(Boolean.parseBoolean(response.getClaims().get(FRONT_CHANNEL_LOGOUT_SESSION_REQUIRED.toString())));
    assertNotNull(response.getClaims().get(FRONT_CHANNEL_LOGOUT_URI.toString()));
    assertTrue(new JSONArray(response.getClaims().get(FRONT_CHANNEL_LOGOUT_URI.toString())).getString(0).equals(logoutUri));
    assertNotNull(response.getClaims().get(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
    assertEquals(SignatureAlgorithm.RS512, SignatureAlgorithm.fromString(response.getClaims().get(ID_TOKEN_SIGNED_RESPONSE_ALG.toString())));
    assertNotNull(response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ALG.toString()));
    assertEquals(KeyEncryptionAlgorithm.RSA1_5, KeyEncryptionAlgorithm.fromName(response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ALG.toString())));
    assertNotNull(response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ENC.toString()));
    assertEquals(BlockEncryptionAlgorithm.A128CBC_PLUS_HS256, BlockEncryptionAlgorithm.fromName(response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ENC.toString())));
    assertNotNull(response.getClaims().get(USERINFO_SIGNED_RESPONSE_ALG.toString()));
    assertEquals(SignatureAlgorithm.RS384, SignatureAlgorithm.fromString(response.getClaims().get(USERINFO_SIGNED_RESPONSE_ALG.toString())));
    assertNotNull(response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ALG.toString()));
    assertEquals(KeyEncryptionAlgorithm.A128KW, KeyEncryptionAlgorithm.fromName(response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ALG.toString())));
    assertNotNull(response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ENC.toString()));
    assertEquals(BlockEncryptionAlgorithm.A128GCM, BlockEncryptionAlgorithm.fromName(response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ENC.toString())));
    assertNotNull(response.getClaims().get(REQUEST_OBJECT_SIGNING_ALG.toString()));
    assertEquals(SignatureAlgorithm.RS256, SignatureAlgorithm.fromString(response.getClaims().get(REQUEST_OBJECT_SIGNING_ALG.toString())));
    assertNotNull(response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ALG.toString()));
    assertEquals(KeyEncryptionAlgorithm.A256KW, KeyEncryptionAlgorithm.fromName(response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ALG.toString())));
    assertNotNull(response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ENC.toString()));
    assertEquals(BlockEncryptionAlgorithm.A256CBC_PLUS_HS512, BlockEncryptionAlgorithm.fromName(response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ENC.toString())));
    assertNotNull(response.getClaims().get(TOKEN_ENDPOINT_AUTH_METHOD.toString()));
    assertEquals(AuthenticationMethod.CLIENT_SECRET_JWT, AuthenticationMethod.fromString(response.getClaims().get(TOKEN_ENDPOINT_AUTH_METHOD.toString())));
    assertNotNull(response.getClaims().get(TOKEN_ENDPOINT_AUTH_SIGNING_ALG.toString()));
    assertEquals(SignatureAlgorithm.ES256, SignatureAlgorithm.fromString(response.getClaims().get(TOKEN_ENDPOINT_AUTH_SIGNING_ALG.toString())));
    JSONArray scopesJsonArray = new JSONArray(response.getClaims().get(SCOPES.toString()));
    List<String> scopes = new ArrayList<String>();
    for (int i = 0; i < scopesJsonArray.length(); i++) {
        scopes.add(scopesJsonArray.get(i).toString());
    }
    assertTrue(scopes.contains("openid"));
    assertTrue(scopes.contains("address"));
    assertTrue(scopes.contains("email"));
    assertTrue(scopes.contains("profile"));
    assertTrue(scopes.contains("phone"));
    assertTrue(scopes.contains("clientinfo"));
    clientId1 = response.getClientId();
    registrationAccessToken1 = response.getRegistrationAccessToken();
    registrationClientUri1 = response.getRegistrationClientUri();
}
Also used : RegisterRequest(org.xdi.oxauth.client.RegisterRequest) RegisterResponse(org.xdi.oxauth.client.RegisterResponse) RegisterClient(org.xdi.oxauth.client.RegisterClient) JSONArray(org.codehaus.jettison.json.JSONArray) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(org.xdi.oxauth.BaseTest)

Example 84 with JSONArray

use of org.codehaus.jettison.json.JSONArray in project oxAuth by GluuFederation.

the class RegisterRestWebServiceImpl method putCustomStuffIntoObject.

/**
     * Puts custom object class and custom attributes in client object for persistence.
     *
     * @param p_client        client object
     * @param p_requestObject request object
     */
private void putCustomStuffIntoObject(Client p_client, JSONObject p_requestObject) throws JSONException {
    // custom object class
    final String customOC = appConfiguration.getDynamicRegistrationCustomObjectClass();
    if (StringUtils.isNotBlank(customOC)) {
        p_client.setCustomObjectClasses(new String[] { customOC });
    }
    // custom attributes (custom attributes must be in custom object class)
    final List<String> attrList = appConfiguration.getDynamicRegistrationCustomAttributes();
    if (attrList != null && !attrList.isEmpty()) {
        for (String attr : attrList) {
            if (p_requestObject.has(attr)) {
                final JSONArray parameterValuesJsonArray = p_requestObject.optJSONArray(attr);
                final List<String> parameterValues = parameterValuesJsonArray != null ? toList(parameterValuesJsonArray) : Arrays.asList(p_requestObject.getString(attr));
                if (parameterValues != null && !parameterValues.isEmpty()) {
                    try {
                        boolean processed = processApplicationAttributes(p_client, attr, parameterValues);
                        if (!processed) {
                            p_client.getCustomAttributes().add(new CustomAttribute(attr, parameterValues));
                        }
                    } catch (Exception e) {
                        log.debug(e.getMessage(), e);
                    }
                }
            }
        }
    }
}
Also used : CustomAttribute(org.xdi.ldap.model.CustomAttribute) JSONArray(org.codehaus.jettison.json.JSONArray) WebApplicationException(javax.ws.rs.WebApplicationException) JSONException(org.codehaus.jettison.json.JSONException)

Example 85 with JSONArray

use of org.codehaus.jettison.json.JSONArray in project oxAuth by GluuFederation.

the class OxAuthCryptoProvider method generateKey.

@Override
public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception {
    KeyPairGenerator keyGen = null;
    if (signatureAlgorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(2048, new SecureRandom());
    } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }
    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();
    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(), expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;
    String alias = UUID.randomUUID().toString();
    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);
    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());
    PublicKey publicKey = keyPair.getPublic();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, Use.SIGNATURE);
    jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);
    return jsonObject;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) JSONArray(org.codehaus.jettison.json.JSONArray) X509Certificate(java.security.cert.X509Certificate) java.security(java.security) JSONObject(org.codehaus.jettison.json.JSONObject) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) PrivateKey(java.security.PrivateKey) FileOutputStream(java.io.FileOutputStream)

Aggregations

JSONArray (org.codehaus.jettison.json.JSONArray)338 JSONObject (org.codehaus.jettison.json.JSONObject)280 Test (org.junit.Test)123 WebResource (com.sun.jersey.api.client.WebResource)65 ClientResponse (com.sun.jersey.api.client.ClientResponse)64 JSONException (org.codehaus.jettison.json.JSONException)64 ArrayList (java.util.ArrayList)38 Test (org.testng.annotations.Test)30 Map (java.util.Map)23 HashMap (java.util.HashMap)22 Vertex (com.tinkerpop.blueprints.Vertex)20 Job (org.apache.hadoop.mapreduce.v2.app.job.Job)20 Produces (javax.ws.rs.Produces)17 MockNM (org.apache.hadoop.yarn.server.resourcemanager.MockNM)14 GET (javax.ws.rs.GET)13 RMApp (org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp)13 IOException (java.io.IOException)12 JobId (org.apache.hadoop.mapreduce.v2.api.records.JobId)12 HashSet (java.util.HashSet)10 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)9