Java Code Examples for org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm

The following examples show how to use org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm. These examples are extracted from open source projects. 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 Project: oxAuth   Author: GluuFederation   File: SignatureTest.java    License: MIT License 6 votes vote down vote up
@Test
public void generateES512Keys() throws Exception {
	showTitle("TEST: generateES512Keys");

	KeyFactory<ECDSAPrivateKey, ECDSAPublicKey> keyFactory = new ECDSAKeyFactory(SignatureAlgorithm.ES512,
			"CN=Test CA Certificate");
	ECDSAPrivateKey privateKey = keyFactory.getPrivateKey();
	ECDSAPublicKey publicKey = keyFactory.getPublicKey();
	Certificate certificate = keyFactory.getCertificate();

	System.out.println("PRIVATE KEY");
	System.out.println(privateKey);
	System.out.println("PUBLIC KEY");
	System.out.println(publicKey);
	System.out.println("CERTIFICATE");
	System.out.println(certificate);

	String signingInput = "Hello World!";
	ECDSASigner ecdsaSigner1 = new ECDSASigner(SignatureAlgorithm.ES512, privateKey);
	String signature = ecdsaSigner1.generateSignature(signingInput);
	ECDSASigner ecdsaSigner2 = new ECDSASigner(SignatureAlgorithm.ES512, publicKey);
	assertTrue(ecdsaSigner2.validateSignature(signingInput, signature));
	ECDSASigner ecdsaSigner3 = new ECDSASigner(SignatureAlgorithm.ES512, certificate);
	assertTrue(ecdsaSigner3.validateSignature(signingInput, signature));
}
 
Example #2
Source Project: oxAuth   Author: GluuFederation   File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "RS384_keyId"})
@Test
public void jwtStateRS384Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateRS384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.RS384, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.RS384);
    assertTrue(validJwt);
}
 
Example #3
Source Project: oxAuth   Author: GluuFederation   File: OxElevenCryptoProvider.java    License: MIT License 6 votes vote down vote up
@Override
public String sign(String signingInput, String keyId, String shardSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
    SignRequest request = new SignRequest();
    request.getSignRequestParam().setSigningInput(signingInput);
    request.getSignRequestParam().setAlias(keyId);
    request.getSignRequestParam().setSharedSecret(shardSecret);
    request.getSignRequestParam().setSignatureAlgorithm(signatureAlgorithm.getName());
    request.setAccessToken(accessToken);

    SignClient client = new SignClient(signEndpoint);
    client.setRequest(request);

    SignResponse response = client.exec();
    if (response.getStatus() == HttpStatus.SC_OK && response.getSignature() != null) {
        return response.getSignature();
    } else {
        throw new Exception(response.getEntity());
    }
}
 
Example #4
Source Project: oxAuth   Author: GluuFederation   File: KeyGenerator.java    License: MIT License 6 votes vote down vote up
public static void generateU2fAttestationKeys(Date startDate, Date expirationDate, String dnName) throws Exception {
    ECDSAKeyFactory keyFactory = new ECDSAKeyFactory(
            SignatureAlgorithm.ES256,
            null);
    Key<ECDSAPrivateKey, ECDSAPublicKey> key = keyFactory.getKey();
    Certificate certificate = keyFactory.generateV3Certificate(startDate, expirationDate, dnName);
    key.setCertificate(certificate);

    key.setKeyType(SignatureAlgorithm.ES256.getFamily().getValue());
    key.setUse(Use.SIGNATURE.toString());
    key.setAlgorithm(SignatureAlgorithm.ES256.getName());
    key.setKeyId(UUID.randomUUID().toString());
    key.setExpirationTime(expirationDate.getTime());
    key.setCurve(SignatureAlgorithm.ES256.getCurve());

    JSONObject jsonKey = key.toJSONObject();
    System.out.println(jsonKey);

    System.out.println("CERTIFICATE:");
    System.out.println(certificate);
}
 
Example #5
Source Project: oxAuth   Author: GluuFederation   File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "ES512_keyId"})
@Test
public void jwtStateES512Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateES512Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.ES512, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES512);
    assertTrue(validJwt);
}
 
Example #6
Source Project: oxAuth   Author: GluuFederation   File: TokenSignaturesHttpTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"clientJwksUri", "ES384_keyId", "dnName", "keyStoreFile", "keyStoreSecret"})
@Test
public void testES384(final String clientJwksUri, final String keyId, final String dnName,
                      final String keyStoreFile, final String keyStoreSecret) {
    try {
        showTitle("Test ES384");

        JwkClient jwkClient = new JwkClient(clientJwksUri);
        JwkResponse jwkResponse = jwkClient.exec();

        String signingInput = "eyJhbGciOiJIUzI1NiJ9.eyJub25jZSI6ICI2Qm9HN1QwR0RUZ2wiLCAiaWRfdG9rZW4iOiB7Im1heF9hZ2UiOiA4NjQwMH0sICJzdGF0ZSI6ICJTVEFURTAiLCAicmVkaXJlY3RfdXJpIjogImh0dHBzOi8vbG9jYWxob3N0L2NhbGxiYWNrMSIsICJ1c2VyaW5mbyI6IHsiY2xhaW1zIjogeyJuYW1lIjogbnVsbH19LCAiY2xpZW50X2lkIjogIkAhMTExMSEwMDA4IUU2NTQuQjQ2MCIsICJzY29wZSI6IFsib3BlbmlkIl0sICJyZXNwb25zZV90eXBlIjogWyJjb2RlIl19";

        OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);
        String encodedSignature = cryptoProvider.sign(signingInput, keyId, null, SignatureAlgorithm.ES384);

        System.out.println("Encoded Signature: " + encodedSignature);

        boolean signatureVerified = cryptoProvider.verifySignature(
                signingInput, encodedSignature, keyId, jwkResponse.getJwks().toJSONObject(), null,
                SignatureAlgorithm.ES384);
        assertTrue(signatureVerified, "Invalid signature");
    } catch (Exception e) {
        fail(e.getMessage(), e);
    }
}
 
Example #7
Source Project: oxAuth   Author: GluuFederation   File: SignatureTest.java    License: MIT License 6 votes vote down vote up
@Test
public void generateES256Keys() throws Exception {
	showTitle("TEST: generateES256Keys");

	KeyFactory<ECDSAPrivateKey, ECDSAPublicKey> keyFactory = new ECDSAKeyFactory(SignatureAlgorithm.ES256,
			"CN=Test CA Certificate");

	Key<ECDSAPrivateKey, ECDSAPublicKey> key = keyFactory.getKey();

	ECDSAPrivateKey privateKey = key.getPrivateKey();
	ECDSAPublicKey publicKey = key.getPublicKey();
	Certificate certificate = key.getCertificate();

	System.out.println(key);

	String signingInput = "Hello World!";
	ECDSASigner ecdsaSigner1 = new ECDSASigner(SignatureAlgorithm.ES256, privateKey);
	String signature = ecdsaSigner1.generateSignature(signingInput);
	ECDSASigner ecdsaSigner2 = new ECDSASigner(SignatureAlgorithm.ES256, publicKey);
	assertTrue(ecdsaSigner2.validateSignature(signingInput, signature));
	ECDSASigner ecdsaSigner3 = new ECDSASigner(SignatureAlgorithm.ES256, certificate);
	assertTrue(ecdsaSigner3.validateSignature(signingInput, signature));
}
 
Example #8
Source Project: oxAuth   Author: GluuFederation   File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "ES384_keyId"})
@Test
public void jwtStateES384Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateES384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.ES384, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES384);
    assertTrue(validJwt);
}
 
Example #9
Source Project: oxd   Author: GluuFederation   File: CheckAccessTokenOperation.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isAccessTokenValid(String p_accessToken, Jwt jwt, OpenIdConfigurationResponse discoveryResponse) {
    try {
        //                final String type = jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE);
        final String algorithm = jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        final String jwkUrl = discoveryResponse.getJwksUri();
        final String kid = jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);

        final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm);

        final RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwkUrl, kid);
        final RSASigner rsaSigner = new RSASigner(signatureAlgorithm, publicKey);
        return rsaSigner.validateAccessToken(p_accessToken, jwt);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return false;
    }
}
 
Example #10
Source Project: oxAuth   Author: GluuFederation   File: OxAuthCryptoProvider.java    License: MIT License 6 votes vote down vote up
public SignatureAlgorithm getSignatureAlgorithm(String alias) throws KeyStoreException {
    Certificate[] chain = keyStore.getCertificateChain(alias);
    if ((chain == null) || chain.length == 0) {
        return null;
    }

    X509Certificate cert = (X509Certificate) chain[0];

    String sighAlgName = cert.getSigAlgName();

    for (SignatureAlgorithm sa : SignatureAlgorithm.values()) {
        if (sighAlgName.equalsIgnoreCase(sa.getAlgorithm())) {
            return sa;
        }
    }

    return null;
}
 
Example #11
Source Project: oxAuth   Author: GluuFederation   File: SignatureTest.java    License: MIT License 6 votes vote down vote up
@Test
public void generateRS256Keys() throws Exception {
	showTitle("TEST: generateRS256Keys");

	KeyFactory<RSAPrivateKey, RSAPublicKey> keyFactory = new RSAKeyFactory(SignatureAlgorithm.RS256,
			"CN=Test CA Certificate");

	Key<RSAPrivateKey, RSAPublicKey> key = keyFactory.getKey();

	RSAPrivateKey privateKey = key.getPrivateKey();
	RSAPublicKey publicKey = key.getPublicKey();
	Certificate certificate = key.getCertificate();

	System.out.println(key);

	String signingInput = "Hello World!";
	RSASigner rsaSigner1 = new RSASigner(SignatureAlgorithm.RS256, privateKey);
	String signature = rsaSigner1.generateSignature(signingInput);
	RSASigner rsaSigner2 = new RSASigner(SignatureAlgorithm.RS256, publicKey);
	assertTrue(rsaSigner2.validateSignature(signingInput, signature));
	RSASigner rsaSigner3 = new RSASigner(SignatureAlgorithm.RS256, certificate);
	assertTrue(rsaSigner3.validateSignature(signingInput, signature));
}
 
Example #12
Source Project: oxAuth   Author: GluuFederation   File: UserInfoRestWebServiceImpl.java    License: MIT License 6 votes vote down vote up
private String getJwtResponse(SignatureAlgorithm signatureAlgorithm, User user, AuthorizationGrant authorizationGrant,
                              Collection<String> scopes) throws Exception {
    log.trace("Building JWT reponse with next scopes {0} for user {1} and user custom attributes {0}", scopes, user.getUserId(), user.getCustomAttributes());

    Jwt jwt = new Jwt();

    // Header
    jwt.getHeader().setType(JwtType.JWT);
    jwt.getHeader().setAlgorithm(signatureAlgorithm);

    String keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(webKeysConfiguration, Algorithm.fromString(signatureAlgorithm.getName()), Use.SIGNATURE);
    if (keyId != null) {
        jwt.getHeader().setKeyId(keyId);
    }

    // Claims
    jwt.setClaims(createJwtClaims(user, authorizationGrant, scopes));

    // Signature
    String sharedSecret = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret());
    String signature = cryptoProvider.sign(jwt.getSigningInput(), jwt.getHeader().getKeyId(), sharedSecret, signatureAlgorithm);
    jwt.setEncodedSignature(signature);

    return jwt.toString();
}
 
Example #13
Source Project: oxAuth   Author: GluuFederation   File: CryptoProviderTest.java    License: MIT License 5 votes vote down vote up
@Test(dependsOnMethods = {"testGenerateKeyRS512"})
public void testSignRS512() {
	try {
		rs512Signature = cryptoProvider.sign(SIGNING_INPUT, rs512Key, null, SignatureAlgorithm.RS512);
		assertNotNull(rs512Signature);
	} catch (Exception e) {
		fail(e.getMessage(), e);
	}
}
 
Example #14
Source Project: oxAuth   Author: GluuFederation   File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS384Step1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS384);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS384Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId2 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #15
Source Project: oxAuth   Author: GluuFederation   File: JwtCrossCheckTest.java    License: MIT License 5 votes vote down vote up
private void crossCheck(OxAuthCryptoProvider cryptoProvider, SignatureAlgorithm signatureAlgorithm) throws Exception {
    final String kid = getKeyIdByAlgorithm(signatureAlgorithm, Use.SIGNATURE, cryptoProvider);

    System.out.println(String.format("Cross check for %s ...", signatureAlgorithm.getName()));
    final String nimbusJwt = createNimbusJwt(cryptoProvider, kid, signatureAlgorithm);
    validate(nimbusJwt, cryptoProvider, kid, signatureAlgorithm);

    final String oxauthJwt = createOxauthJwt(cryptoProvider, kid, signatureAlgorithm);
    validate(oxauthJwt, cryptoProvider, kid, signatureAlgorithm);
    System.out.println(String.format("Finished cross check for %s.", signatureAlgorithm.getName()));
}
 
Example #16
Source Project: oxAuth   Author: GluuFederation   File: AuthorizationAction.java    License: MIT License 5 votes vote down vote up
public boolean isKeyIdRequired() {
    if (isJWSSelected()) {
        return requestObjectSigningAlg == SignatureAlgorithm.RS256
                || requestObjectSigningAlg == SignatureAlgorithm.RS384
                || requestObjectSigningAlg == SignatureAlgorithm.RS512
                || requestObjectSigningAlg == SignatureAlgorithm.ES256
                || requestObjectSigningAlg == SignatureAlgorithm.ES384
                || requestObjectSigningAlg == SignatureAlgorithm.ES512;
    } else {
        return requestObjectEncryptionAlg == KeyEncryptionAlgorithm.RSA1_5
                || requestObjectEncryptionAlg == KeyEncryptionAlgorithm.RSA_OAEP;
    }
}
 
Example #17
Source Project: oxAuth   Author: GluuFederation   File: AuthorizationAction.java    License: MIT License 5 votes vote down vote up
public boolean isKeyStoreRequired() {
    if (isJWSSelected()) {
        return requestObjectSigningAlg == SignatureAlgorithm.RS256
                || requestObjectSigningAlg == SignatureAlgorithm.RS384
                || requestObjectSigningAlg == SignatureAlgorithm.RS512
                || requestObjectSigningAlg == SignatureAlgorithm.ES256
                || requestObjectSigningAlg == SignatureAlgorithm.ES384
                || requestObjectSigningAlg == SignatureAlgorithm.ES512;
    } else {
        return false;
    }
}
 
Example #18
Source Project: oxAuth   Author: GluuFederation   File: JwtCrossCheckTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "dnName", "keyStoreFile", "keyStoreSecret" })
@Test
public void rs512CrossCheck(final String dnName,
                            final String keyStoreFile,
                            final String keyStoreSecret) throws Exception {
    crossCheck(new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName), SignatureAlgorithm.RS512);
}
 
Example #19
Source Project: oxAuth   Author: GluuFederation   File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS256Step1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS256Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId1 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #20
Source Project: oxAuth   Author: GluuFederation   File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS512X509CertStep1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS512);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS512X509CertStep1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId6 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #21
Source Project: oxAuth   Author: GluuFederation   File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS384X509CertStep1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS384);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS384X509CertStep1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId5 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #22
Source Project: oxAuth   Author: GluuFederation   File: JwtHeader.java    License: MIT License 5 votes vote down vote up
/**
 * Identifies the cryptographic algorithm used to secure the JWS.
 *
 * @param algorithm The cryptographic algorithm.
 */
public JwtHeader setAlgorithm(SignatureAlgorithm algorithm) {
    if (algorithm == null) {
        setNullClaim(ALGORITHM);
    } else {
        setClaim(ALGORITHM, algorithm.toString());
    }
    return this;
}
 
Example #23
Source Project: oxAuth   Author: GluuFederation   File: CibaPollModeJwtAuthRequestTests.java    License: MIT License 5 votes vote down vote up
@Parameters({"PS384_keyId", "userId", "dnName", "keyStoreFile", "keyStoreSecret", "clientJwksUri"})
@Test
public void pollFlowPS384HappyFlow(final String keyId, final String userId, final String dnName,
                                    final String keyStoreFile, final String keyStoreSecret,
                                    final String clientJwksUri) throws Exception {
    showTitle("pollFlowPS384HappyFlow");
    registerPollClient(clientJwksUri, BackchannelTokenDeliveryMode.POLL, AsymmetricSignatureAlgorithm.PS384);

    JwtAuthorizationRequest jwtAuthorizationRequest = createJwtRequest(keyStoreFile, keyStoreSecret, dnName,
            userId, keyId, SignatureAlgorithm.PS384);

    processCibaAuthorizationEndpointSuccessfulCall(jwtAuthorizationRequest.getEncodedJwt(),
            registerResponse.getClientId(), registerResponse.getClientSecret());
}
 
Example #24
Source Project: oxd   Author: GluuFederation   File: OpClientFactoryMockImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public synchronized RSASigner createRSASigner(SignatureAlgorithm signatureAlgorithm, RSAPublicKey rsaPublicKey) {
    Optional<RSASigner> rsaSigner = Optional.ofNullable((RSASigner) opClientCache.getIfPresent("RSASigner"));
    RSASigner client = null;
    if (!rsaSigner.isPresent()) {
        client = mock(RSASigner.class);
        when(client.validate(any())).thenReturn(true);
        when(client.validateAccessToken(any(), any())).thenReturn(true);
        opClientCache.put("RSASigner", client);
    } else {
        client = (RSASigner) opClientCache.getIfPresent("RSASigner");
    }

    return client;
}
 
Example #25
Source Project: oxAuth   Author: GluuFederation   File: CibaPollModeJwtAuthRequestTests.java    License: MIT License 5 votes vote down vote up
@Parameters({"ES384_keyId", "userId", "dnName", "keyStoreFile", "keyStoreSecret", "clientJwksUri"})
@Test
public void pollFlowES384HappyFlow(final String keyId, final String userId, final String dnName,
                                    final String keyStoreFile, final String keyStoreSecret,
                                    final String clientJwksUri) throws Exception {
    showTitle("pollFlowES384HappyFlow");
    registerPollClient(clientJwksUri, BackchannelTokenDeliveryMode.POLL, AsymmetricSignatureAlgorithm.ES384);

    JwtAuthorizationRequest jwtAuthorizationRequest = createJwtRequest(keyStoreFile, keyStoreSecret, dnName,
            userId, keyId, SignatureAlgorithm.ES384);

    processCibaAuthorizationEndpointSuccessfulCall(jwtAuthorizationRequest.getEncodedJwt(),
            registerResponse.getClientId(), registerResponse.getClientSecret());
}
 
Example #26
Source Project: oxAuth   Author: GluuFederation   File: CryptoProviderTest.java    License: MIT License 5 votes vote down vote up
@Test(dependsOnMethods = {"testSignRS256"})
public void testVerifyRS256() {
	try {
		boolean signatureVerified = cryptoProvider.verifySignature(SIGNING_INPUT, rs256Signature, rs256Key, null,
				null, SignatureAlgorithm.RS256);
		assertTrue(signatureVerified);
	} catch (Exception e) {
		fail(e.getMessage(), e);
	}
}
 
Example #27
Source Project: oxAuth   Author: GluuFederation   File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS256X509CertStep1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodRS256X509CertStep1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId4 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #28
Source Project: oxAuth   Author: GluuFederation   File: OpenIDRequestObjectEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris" })
@Test
public void requestParameterMethodAlgNoneStep1(final String registerPath, final String redirectUris)
		throws Exception {

	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.NONE);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodAlgNoneStep1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId3 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #29
Source Project: oxAuth   Author: GluuFederation   File: JwtCrossCheckTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "dnName", "keyStoreFile", "keyStoreSecret" })
@Test
public void rs256CrossCheck(final String dnName,
                          final String keyStoreFile,
                          final String keyStoreSecret) throws Exception {
    crossCheck(new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName), SignatureAlgorithm.RS256);
}
 
Example #30
Source Project: oxTrust   Author: GluuFederation   File: AuthenticationFilter.java    License: MIT License 4 votes vote down vote up
public String getOAuthRedirectUrl(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    String authorizeUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, null);
    String clientScopes = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, null);

    String clientId = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_ID, null);
    String clientSecret = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, null);
    if (clientSecret != null) {
        try {
            clientSecret = StringEncrypter.defaultInstance().decrypt(clientSecret, Configuration.instance().getCryptoPropertyValue());
        } catch (EncryptionException ex) {
            log.error("Failed to decrypt property: " + Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, ex);
        }
    }

    String redirectUri = constructRedirectUrl(request);

    List<String> scopes = Arrays.asList(clientScopes.split(StringUtils.SPACE));
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    // Lookup for relying party ID
    final String key = request.getParameter(ExternalAuthentication.CONVERSATION_KEY);
    request.getSession().setAttribute(SESSION_CONVERSATION_KEY, key);
    ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, request);

    String relyingPartyId = "";
    final RelyingPartyContext relyingPartyCtx = prc.getSubcontext(RelyingPartyContext.class);
    if (relyingPartyCtx != null) {
        relyingPartyId = relyingPartyCtx.getRelyingPartyId();
        log.info("relyingPartyId found: " + relyingPartyId);
    } else
        log.warn("No RelyingPartyContext was available");

    // JWT
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    JwtState jwtState = new JwtState(SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    if (relyingPartyId != null && !"".equals(relyingPartyId)) {
        String additionalClaims = String.format("{relyingPartyId: '%s'}", relyingPartyId);
        jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    } else
        log.warn("No relyingPartyId was available");
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    Cookie currentShibstateCookie = getCurrentShibstateCookie(request);
    if (currentShibstateCookie != null) {
        String requestUri = decodeCookieValue(currentShibstateCookie.getValue());
        log.debug("requestUri = \"" + requestUri + "\"");

        String authenticationMode = determineAuthenticationMode(requestUri);

        if (StringHelper.isNotEmpty(authenticationMode)) {
            log.debug("acr_values = \"" + authenticationMode + "\"");
            authorizationRequest.setAcrValues(Arrays.asList(authenticationMode));
            updateShibstateCookie(response, currentShibstateCookie, requestUri, "/" + Configuration.OXAUTH_ACR_VALUES + "/" + authenticationMode);
        }
    }

    // Store for validation in session
    final HttpSession session = request.getSession(false);
    session.setAttribute(Configuration.SESSION_AUTH_STATE, encodedState);
    session.setAttribute(Configuration.SESSION_AUTH_NONCE, nonce);

    return authorizeUrl + "?" + authorizationRequest.getQueryString();
}