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

The following examples show how to use org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm#ES512 . 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", "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 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: 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 4
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 5
Source File: HashUtil.java    From oxAuth with MIT License 5 votes vote down vote up
public static String getHash(String input, SignatureAlgorithm signatureAlgorithm) {
    try {
        final byte[] digest;
        if (signatureAlgorithm == SignatureAlgorithm.HS256 ||
                signatureAlgorithm == SignatureAlgorithm.RS256 ||
                signatureAlgorithm == SignatureAlgorithm.PS256 ||
                signatureAlgorithm == SignatureAlgorithm.ES256) {
            digest = JwtUtil.getMessageDigestSHA256(input);
        } else if (signatureAlgorithm == SignatureAlgorithm.HS384 ||
                signatureAlgorithm == SignatureAlgorithm.RS384 ||
                signatureAlgorithm == SignatureAlgorithm.PS384 ||
                signatureAlgorithm == SignatureAlgorithm.ES384) {
            digest = JwtUtil.getMessageDigestSHA384(input);
        } else if (signatureAlgorithm == SignatureAlgorithm.HS512 ||
                signatureAlgorithm == SignatureAlgorithm.RS512 ||
                signatureAlgorithm == SignatureAlgorithm.PS512 ||
                signatureAlgorithm == SignatureAlgorithm.ES512) {
            digest = JwtUtil.getMessageDigestSHA512(input);
        } else { // Default
            digest = JwtUtil.getMessageDigestSHA256(input);
        }

        if (digest != null) {
            byte[] lefMostHalf = new byte[digest.length / 2];
            System.arraycopy(digest, 0, lefMostHalf, 0, lefMostHalf.length);
            return Base64Util.base64urlencode(lefMostHalf);
        }
    } catch (Exception e) {
        log.error("Failed to calculate hash.", e);
    }

    return null;
}
 
Example 6
Source File: EncodeClaimsInStateParameter.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri",
        "keyStoreFile", "keyStoreSecret", "dnName", "ES512_keyId"})
@Test
public void encodeClaimsInStateParameterES512(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri, final String keyStoreFile, final String keyStoreSecret,
        final String dnName, final String keyId) throws Exception {
    showTitle("encodeClaimsInStateParameterES512");

    List<ResponseType> responseTypes = Arrays.asList(
            ResponseType.TOKEN,
            ResponseType.ID_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();

    // 2. Request authorization
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    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();

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

    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.getIdToken(), "The idToken is null");
    assertNotNull(authorizationResponse.getState(), "The state is null");

    String state = authorizationResponse.getState();

    // 3. Validate state
    Jwt jwt = Jwt.parse(state);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES512);
    assertTrue(validJwt);
}
 
Example 7
Source File: OpenIDRequestObjectHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUri", "redirectUris", "clientJwksUri",
        "ES512_keyId", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestParameterMethodES512(
        final String userId, final String userSecret, final String redirectUri, final String redirectUris,
        final String jwksUri, final String keyId, final String dnName, final String keyStoreFile,
        final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("requestParameterMethodES512");

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

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.ES512);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    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());

    String clientId = response.getClientId();

    // 2. Request authorization
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

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

    AuthorizationRequest request = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    request.setState(state);
    request.setAuthUsername(userId);
    request.setAuthPassword(userSecret);
    request.getPrompts().add(Prompt.NONE);

    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(request, SignatureAlgorithm.ES512, cryptoProvider);
    jwtAuthorizationRequest.setKeyId(keyId);
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, ClaimValue.createValueList(new String[]{ACR_VALUE})));
    jwtAuthorizationRequest.getIdTokenMember().setMaxAge(86400);
    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    request.setRequest(authJwt);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(request);
    AuthorizationResponse response1 = authorizeClient.exec();

    showClient(authorizeClient);
    assertEquals(response1.getStatus(), 302, "Unexpected response code: " + response1.getStatus());
    assertNotNull(response1.getLocation(), "The location is null");
    assertNotNull(response1.getAccessToken(), "The accessToken is null");
    assertNotNull(response1.getTokenType(), "The tokenType is null");
    assertNotNull(response1.getIdToken(), "The idToken is null");
    assertNotNull(response1.getState(), "The state is null");

    String accessToken = response1.getAccessToken();

    // 3. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse response3 = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(response3.getStatus(), 200, "Unexpected response code: " + response3.getStatus());
    assertNotNull(response3.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(response3.getClaim(JwtClaimName.NAME));
    assertNotNull(response3.getClaim(JwtClaimName.GIVEN_NAME));
    assertNotNull(response3.getClaim(JwtClaimName.FAMILY_NAME));
    assertNotNull(response3.getClaim(JwtClaimName.EMAIL));
    assertNotNull(response3.getClaim(JwtClaimName.ZONEINFO));
    assertNotNull(response3.getClaim(JwtClaimName.LOCALE));
}
 
Example 8
Source File: OpenIDRequestObjectHttpTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"userId", "userSecret", "redirectUri", "redirectUris", "clientJwksUri",
        "ES512_keyId", "dnName", "keyStoreFile", "keyStoreSecret", "sectorIdentifierUri"})
@Test
public void requestParameterMethodES512X509Cert(
        final String userId, final String userSecret, final String redirectUri, final String redirectUris,
        final String jwksUri, final String keyId, final String dnName, final String keyStoreFile,
        final String keyStoreSecret, final String sectorIdentifierUri) throws Exception {
    showTitle("requestParameterMethodES512X509Cert");

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

    // 1. Dynamic Client Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setJwksUri(jwksUri);
    registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.ES512);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    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());

    String clientId = response.getClientId();

    // 2. Request authorization
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

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

    AuthorizationRequest request = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    request.setState(state);
    request.setAuthUsername(userId);
    request.setAuthPassword(userSecret);
    request.getPrompts().add(Prompt.NONE);

    JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(request, SignatureAlgorithm.ES512, cryptoProvider);
    jwtAuthorizationRequest.setKeyId(keyId);
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
    jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
    jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, ClaimValue.createValueList(new String[]{ACR_VALUE})));
    jwtAuthorizationRequest.getIdTokenMember().setMaxAge(86400);
    String authJwt = jwtAuthorizationRequest.getEncodedJwt();
    request.setRequest(authJwt);

    AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint);
    authorizeClient.setRequest(request);
    AuthorizationResponse response1 = authorizeClient.exec();

    showClient(authorizeClient);
    assertEquals(response1.getStatus(), 302, "Unexpected response code: " + response1.getStatus());
    assertNotNull(response1.getLocation(), "The location is null");
    assertNotNull(response1.getAccessToken(), "The accessToken is null");
    assertNotNull(response1.getTokenType(), "The tokenType is null");
    assertNotNull(response1.getIdToken(), "The idToken is null");
    assertNotNull(response1.getState(), "The state is null");

    String accessToken = response1.getAccessToken();

    // 3. Request user info
    UserInfoClient userInfoClient = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse response3 = userInfoClient.execUserInfo(accessToken);

    showClient(userInfoClient);
    assertEquals(response3.getStatus(), 200, "Unexpected response code: " + response3.getStatus());
    assertNotNull(response3.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(response3.getClaim(JwtClaimName.NAME));
    assertNotNull(response3.getClaim(JwtClaimName.GIVEN_NAME));
    assertNotNull(response3.getClaim(JwtClaimName.FAMILY_NAME));
    assertNotNull(response3.getClaim(JwtClaimName.EMAIL));
    assertNotNull(response3.getClaim(JwtClaimName.ZONEINFO));
    assertNotNull(response3.getClaim(JwtClaimName.LOCALE));
}
 
Example 9
Source File: UsesAsymmetricIdTokenSignatures.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"})
@Test
public void usesAsymmetricIdTokenSignaturesES512(
        final String redirectUris, final String userId, final String userSecret, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Uses Asymmetric ID Token Signatures ES512");

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

    // 1. Registration
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.ES512);
    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.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();

    // 2. Request Authorization
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String nonce = UUID.randomUUID().toString();
    String state = UUID.randomUUID().toString();

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

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

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getIdToken());
    assertNotNull(authorizationResponse.getState());

    String idToken = authorizationResponse.getIdToken();

    // 3. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(
            jwksUri,
            jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    ECDSASigner ecdsaSigner = new ECDSASigner(SignatureAlgorithm.ES512, publicKey);
    assertTrue(ecdsaSigner.validate(jwt));
}
 
Example 10
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES512_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES512Step1")
public void requestParameterMethodES512Step2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {

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

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

		AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId3, scopes,
				redirectUri, nonce);
		authorizationRequest.setState(state);
		authorizationRequest.getPrompts().add(Prompt.NONE);
		authorizationRequest.setAuthUsername(userId);
		authorizationRequest.setAuthPassword(userSecret);

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES512, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES512Step2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 11
Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({ "authorizePath", "userId", "userSecret", "redirectUri", "ES512_keyId", "dnName", "keyStoreFile",
		"keyStoreSecret" })
@Test(dependsOnMethods = "requestParameterMethodES512X509CertStep1")
public void requestParameterMethodES512X509CertStep2(final String authorizePath, final String userId,
		final String userSecret, final String redirectUri, final String keyId, final String dnName,
		final String keyStoreFile, final String keyStoreSecret) throws Exception {
	Builder request = null;
	try {
		OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

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

		AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId6, scopes,
				redirectUri, nonce);
		authorizationRequest.setState(state);
		authorizationRequest.getPrompts().add(Prompt.NONE);
		authorizationRequest.setAuthUsername(userId);
		authorizationRequest.setAuthPassword(userSecret);

		JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest,
				SignatureAlgorithm.ES512, cryptoProvider);
		jwtAuthorizationRequest.setKeyId(keyId);
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.NAME, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.NICKNAME, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL, ClaimValue.createNull()));
		jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.EMAIL_VERIFIED, ClaimValue.createNull()));
		jwtAuthorizationRequest
				.addUserInfoClaim(new Claim(JwtClaimName.PICTURE, ClaimValue.createEssential(false)));
		jwtAuthorizationRequest
				.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_TIME, ClaimValue.createNull()));
		jwtAuthorizationRequest.addIdTokenClaim(new Claim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
				ClaimValue.createValueList(new String[] { ACR_VALUE })));
		String authJwt = jwtAuthorizationRequest.getEncodedJwt();
		authorizationRequest.setRequest(authJwt);
		System.out.println("Request JWT: " + authJwt);

		request = ResteasyClientBuilder.newClient()
				.target(url.toString() + authorizePath + "?" + authorizationRequest.getQueryString()).request();
		request.header("Authorization", "Basic " + authorizationRequest.getEncodedCredentials());
		request.header("Accept", MediaType.TEXT_PLAIN);
	} catch (Exception ex) {
		fail(ex.getMessage(), ex);
	}

	Response response = request.get();
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES512X509CertStep2", response, entity);

	assertEquals(response.getStatus(), 302, "Unexpected response code.");
	assertNotNull(response.getLocation(), "Unexpected result: " + response.getLocation());

	try {
		URI uri = new URI(response.getLocation().toString());
		assertNotNull(uri.getFragment(), "Query string is null");

		Map<String, String> params = QueryStringDecoder.decode(uri.getFragment());

		assertNotNull(params.get("access_token"), "The accessToken is null");
		assertNotNull(params.get("scope"), "The scope is null");
		assertNotNull(params.get("state"), "The state is null");
	} catch (URISyntaxException e) {
		fail(e.getMessage(), e);
	}
}
 
Example 12
Source File: JwtUtil.java    From oxAuth with MIT License 4 votes vote down vote up
public static PublicKey getPublicKey(
        String jwksUri, String jwks, SignatureAlgorithm signatureAlgorithm, String keyId) {
    log.debug("Retrieving JWK...");

    JSONObject jsonKeyValue = getJsonKey(jwksUri, jwks, keyId);

    if (jsonKeyValue == null) {
        return null;
    }

    org.gluu.oxauth.model.crypto.PublicKey publicKey = null;

    try {
        String resultKeyId = jsonKeyValue.getString(KEY_ID);
        if (signatureAlgorithm == null) {
            signatureAlgorithm = SignatureAlgorithm.fromString(jsonKeyValue.getString(ALGORITHM));
            if (signatureAlgorithm == null) {
                log.error(String.format("Failed to determine key '%s' signature algorithm", resultKeyId));
                return null;
            }
        }

        JSONObject jsonPublicKey = jsonKeyValue;
        if (jsonKeyValue.has(PUBLIC_KEY)) {
            // Use internal jwks.json format
            jsonPublicKey = jsonKeyValue.getJSONObject(PUBLIC_KEY);
        }

        if (signatureAlgorithm == SignatureAlgorithm.RS256 || signatureAlgorithm == SignatureAlgorithm.RS384 || signatureAlgorithm == SignatureAlgorithm.RS512) {
            //String alg = jsonKeyValue.getString(ALGORITHM);
            //String use = jsonKeyValue.getString(KEY_USE);
            String exp = jsonPublicKey.getString(EXPONENT);
            String mod = jsonPublicKey.getString(MODULUS);

            BigInteger publicExponent = new BigInteger(1, Base64Util.base64urldecode(exp));
            BigInteger modulus = new BigInteger(1, Base64Util.base64urldecode(mod));

            publicKey = new RSAPublicKey(modulus, publicExponent);
        } else if (signatureAlgorithm == SignatureAlgorithm.ES256 || signatureAlgorithm == SignatureAlgorithm.ES384 || signatureAlgorithm == SignatureAlgorithm.ES512) {
            //String alg = jsonKeyValue.getString(ALGORITHM);
            //String use = jsonKeyValue.getString(KEY_USE);
            //String crv = jsonKeyValue.getString(CURVE);
            String xx = jsonPublicKey.getString(X);
            String yy = jsonPublicKey.getString(Y);

            BigInteger x = new BigInteger(1, Base64Util.base64urldecode(xx));
            BigInteger y = new BigInteger(1, Base64Util.base64urldecode(yy));

            publicKey = new ECDSAPublicKey(signatureAlgorithm, x, y);
        }

        if (publicKey != null && jsonKeyValue.has(CERTIFICATE_CHAIN)) {
            final String BEGIN = "-----BEGIN CERTIFICATE-----";
            final String END = "-----END CERTIFICATE-----";

            JSONArray certChain = jsonKeyValue.getJSONArray(CERTIFICATE_CHAIN);
            String certificateString = BEGIN + "\n" + certChain.getString(0) + "\n" + END;
            StringReader sr = new StringReader(certificateString);
            PEMParser pemReader = new PEMParser(sr);
            X509Certificate cert = (X509CertificateObject) pemReader.readObject();
            Certificate certificate = new Certificate(signatureAlgorithm, cert);
            publicKey.setCertificate(certificate);
        }
        if (publicKey != null) {
            publicKey.setKeyId(resultKeyId);
            publicKey.setSignatureAlgorithm(signatureAlgorithm);
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }

    return publicKey;
}