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

The following examples show how to use org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm. 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: EncodeClaimsInStateParameter.java    From oxAuth with 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 #2
Source File: SignatureTest.java    From oxAuth with 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 #3
Source File: SignatureTest.java    From oxAuth with 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 #4
Source File: UserInfoRestWebServiceImpl.java    From oxAuth with 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 #5
Source File: EncodeClaimsInStateParameter.java    From oxAuth with 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 #6
Source File: OxAuthCryptoProvider.java    From oxAuth with 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 #7
Source File: TokenSignaturesHttpTest.java    From oxAuth with 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 #8
Source File: EncodeClaimsInStateParameter.java    From oxAuth with 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 #9
Source File: SignatureTest.java    From oxAuth with 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 #10
Source File: KeyGenerator.java    From oxAuth with 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 #11
Source File: OxElevenCryptoProvider.java    From oxAuth with 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 #12
Source File: CheckAccessTokenOperation.java    From oxd with 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 #13
Source File: JwtCrossCheckTest.java    From oxAuth with 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 #14
Source File: OpenIDRequestObjectEmbeddedTest.java    From oxAuth with 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 #15
Source File: CryptoProviderTest.java    From oxAuth with 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 #16
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with 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 #17
Source File: JwtCrossCheckTest.java    From oxAuth with 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 #18
Source File: OpClientFactoryMockImpl.java    From oxd with 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 #19
Source File: AuthorizationAction.java    From oxAuth with 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 #20
Source File: JwtCrossCheckTest.java    From oxAuth with 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 #21
Source File: AuthorizationAction.java    From oxAuth with 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 #22
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with 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 #23
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with 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 #24
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with 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 #25
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with 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 #26
Source File: JwtHeader.java    From oxAuth with 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 #27
Source File: CryptoProviderTest.java    From oxAuth with 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 #28
Source File: CibaPollModeJwtAuthRequestTests.java    From oxAuth with 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 #29
Source File: CibaPollModeJwtAuthRequestTests.java    From oxAuth with 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 #30
Source File: OpenIDRequestObjectHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void requestParameterMethod5(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("requestParameterMethod5");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    // 2. Request authorization
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();

    List<String> scopes = Arrays.asList("openid");
    String state = UUID.randomUUID().toString();
    String nonce = UUID.randomUUID().toString();

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

    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(
            authorizationRequest, SignatureAlgorithm.HS512, clientSecret, cryptoProvider);
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.SUBJECT_IDENTIFIER, ClaimValue.createSingleValue(userId)));
    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    authorizationRequest.setRequest(authJwt);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation(), "The location is null");
    assertNotNull(authorizationResponse.getAccessToken(), "The accessToken is null");
    assertNotNull(authorizationResponse.getTokenType(), "The tokenType is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");
}