org.opensaml.security.credential.Credential Java Examples

The following examples show how to use org.opensaml.security.credential.Credential. 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: SamlSingleLogoutFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
SamlSingleLogoutFunction(SamlEndpoint endpoint, String entityId,
                         Credential signingCredential,
                         String signatureAlgorithm,
                         Map<String, SamlIdentityProviderConfig> idpConfigs,
                         @Nullable SamlIdentityProviderConfig defaultIdpConfig,
                         SamlRequestIdManager requestIdManager,
                         SamlSingleLogoutHandler sloHandler) {
    this.endpoint = endpoint;
    this.entityId = entityId;
    this.signingCredential = signingCredential;
    this.signatureAlgorithm = signatureAlgorithm;
    this.idpConfigs = idpConfigs;
    this.defaultIdpConfig = defaultIdpConfig;
    this.requestIdManager = requestIdManager;
    this.sloHandler = sloHandler;
}
 
Example #2
Source File: SamlIdentityProviderConfig.java    From armeria with Apache License 2.0 6 votes vote down vote up
SamlIdentityProviderConfig(String entityId,
                           Credential signingCredential,
                           Credential encryptionCredential,
                           SamlEndpoint ssoEndpoint,
                           @Nullable SamlEndpoint sloReqEndpoint,
                           @Nullable SamlEndpoint sloResEndpoint,
                           @Nullable SamlEndpoint acsEndpoint,
                           SamlNameIdPolicy nameIdPolicy) {
    this.entityId = requireNonNull(entityId, "entityId");
    this.signingCredential = requireNonNull(signingCredential, "signingCredential");
    this.encryptionCredential = requireNonNull(encryptionCredential, "encryptionCredential");
    this.ssoEndpoint = requireNonNull(ssoEndpoint, "ssoEndpoint");
    this.sloReqEndpoint = sloReqEndpoint;
    this.sloResEndpoint = sloResEndpoint;
    this.acsEndpoint = acsEndpoint;
    this.nameIdPolicy = requireNonNull(nameIdPolicy, "nameIdPolicy");
}
 
Example #3
Source File: SamlMessageUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
static void validateSignature(Credential validationCredential, SignableSAMLObject signableObj) {
    requireNonNull(validationCredential, "validationCredential");
    requireNonNull(signableObj, "signableObj");

    // Skip signature validation if the object is not signed.
    if (!signableObj.isSigned()) {
        return;
    }

    final Signature signature = signableObj.getSignature();
    if (signature == null) {
        throw new InvalidSamlRequestException("failed to validate a signature because no signature exists");
    }

    try {
        signatureProfileValidator.validate(signature);
        SignatureValidator.validate(signature, validationCredential);
    } catch (SignatureException e) {
        throw new InvalidSamlRequestException("failed to validate a signature", e);
    }
}
 
Example #4
Source File: AssertionHelper.java    From verify-service-provider with MIT License 6 votes vote down vote up
public static List<String> getReEncryptedKeys(Response countryResponse) {
    PublicKeyFactory publicKeyFactory = new PublicKeyFactory(new X509CertificateFactory());
    PrivateKey privateKey = new PrivateKeyFactory().createPrivateKey(Base64.decodeBase64(TestCertificateStrings.PRIVATE_SIGNING_KEYS.get(TEST_RP)));
    PublicKey publicKey = publicKeyFactory.createPublicKey(TestCertificateStrings.getPrimaryPublicEncryptionCert(TEST_RP));

    PrivateKey privateEncryptionKey = new PrivateKeyFactory().createPrivateKey(Base64.decodeBase64(TEST_RP_PRIVATE_ENCRYPTION_KEY));
    PublicKey publicEncryptionKey = publicKeyFactory.createPublicKey(TEST_RP_PUBLIC_ENCRYPTION_CERT);

    KeyPair encryptionKeyPair = new KeyPair(publicEncryptionKey, privateEncryptionKey);

    IdaKeyStoreCredentialRetriever keyStoreCredentialRetriever = new IdaKeyStoreCredentialRetriever(
            new IdaKeyStore(new KeyPair(publicKey, privateKey), Arrays.asList(encryptionKeyPair))
    );
    List<Credential> credentials = keyStoreCredentialRetriever.getDecryptingCredentials();
    Decrypter decrypter = new DecrypterFactory().createDecrypter(credentials);
    AssertionDecrypter assertionDecrypter = new AssertionDecrypter(new EncryptionAlgorithmValidator(), decrypter);

    KeyStoreBackedEncryptionCredentialResolver credentialResolver = mock(KeyStoreBackedEncryptionCredentialResolver.class);
    Credential credential = new TestCredentialFactory(TEST_RP_PUBLIC_ENCRYPTION_CERT, null).getEncryptingCredential();
    when(credentialResolver.getEncryptingCredential(TEST_RP)).thenReturn(credential);
    SecretKeyEncrypter secretKeyEncrypter = new SecretKeyEncrypter(credentialResolver);

    return assertionDecrypter.getReEncryptedKeys(new ValidatedResponse(countryResponse), secretKeyEncrypter, TEST_RP);
}
 
Example #5
Source File: SamlIdentityProviderConfigBuilder.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a {@link SamlIdentityProviderConfig}.
 */
SamlIdentityProviderConfig build(CredentialResolverAdapter credentialResolver) {
    checkState(entityId != null, "entity ID of the identity provider is not set");

    // Use the entityId as a default key name.
    final Credential signing = credentialResolver.apply(firstNonNull(signingKey, entityId));
    final Credential encryption = credentialResolver.apply(firstNonNull(encryptionKey, entityId));

    return new SamlIdentityProviderConfig(entityId,
                                          signing,
                                          encryption,
                                          ssoEndpoint,
                                          sloReqEndpoint,
                                          sloResEndpoint,
                                          acsEndpoint,
                                          nameIdPolicy);
}
 
Example #6
Source File: ValidatorUtils.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Validate boolean.
 *
 * @param signature   the signature
 * @param credentials the credentials
 * @return the boolean
 */
private static boolean validate(Signature signature, List<Credential> credentials) {
  if (signature == null) {
    return false;
  }

  // It's fine if any of the credentials match the signature
  return credentials
      .stream()
      .anyMatch(
          credential -> {
            try {
              SignatureValidator.validate(signature, credential);
              return true;
            } catch (SignatureException ex) {
              return false;
            }
          });
}
 
Example #7
Source File: SamlAssertionConsumerFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static Assertion decryptAssertion(EncryptedAssertion encryptedAssertion,
                                          Credential decryptionCredential) {
    final StaticKeyInfoCredentialResolver keyInfoCredentialResolver =
            new StaticKeyInfoCredentialResolver(decryptionCredential);
    final Decrypter decrypter =
            new Decrypter(null, keyInfoCredentialResolver, new InlineEncryptedKeyResolver());
    decrypter.setRootInNewDocument(true);
    try {
        return decrypter.decrypt(encryptedAssertion);
    } catch (DecryptionException e) {
        throw new InvalidSamlRequestException("failed to decrypt an assertion", e);
    }
}
 
Example #8
Source File: ValidatorUtils.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Validate.
 *
 * @param logoutRequest       the response
 * @param responseIssuer the response issuer
 * @param credentials    the credentials
 * @throws SamlException the saml exception
 */
public static void validate(
    LogoutRequest logoutRequest,
    String responseIssuer,
    List<Credential> credentials,
    String nameID)
    throws SamlException {
  validateLogoutRequest(logoutRequest, responseIssuer, nameID);
  validateSignature(logoutRequest, credentials);
}
 
Example #9
Source File: ValidatorUtils.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Validate.
 *
 * @param response       the response
 * @param responseIssuer the response issuer
 * @param credentials    the credentials
 * @param now            the current date time (for unit test only)
 * @param notBeforeSkew  the notBeforeSkew
 * @throws SamlException the saml exception
 */
public static void validate(
    Response response,
    String responseIssuer,
    List<Credential> credentials,
    DateTime now,
    long notBeforeSkew)
    throws SamlException {
  validateResponse(response, responseIssuer);
  validateAssertion(response, responseIssuer, now, notBeforeSkew);
  validateSignature(response, credentials);
  validateAssertionSignature(response, credentials);
}
 
Example #10
Source File: ValidatorUtils.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Validate assertion signature.
 *
 * @param response    the response
 * @param credentials the credentials
 * @throws SamlException the saml exception
 */
private static void validateAssertionSignature(Response response, List<Credential> credentials)
    throws SamlException {
  Signature assertionSignature = response.getAssertions().get(0).getSignature();

  if (response.getSignature() == null && assertionSignature == null) {
    throw new SamlException("No signature is present in either response or assertion");
  }

  if (assertionSignature != null && !validate(assertionSignature, credentials)) {
    throw new SamlException("The assertion signature is invalid");
  }
}
 
Example #11
Source File: SamlServiceProvider.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * A class which helps a {@link Server} have a SAML-based authentication.
 */
SamlServiceProvider(Authorizer<HttpRequest> authorizer,
                    String entityId,
                    @Nullable String hostname,
                    Credential signingCredential,
                    Credential encryptionCredential,
                    String signatureAlgorithm,
                    SamlPortConfigAutoFiller portConfigAutoFiller,
                    String metadataPath,
                    Map<String, SamlIdentityProviderConfig> idpConfigs,
                    @Nullable SamlIdentityProviderConfig defaultIdpConfig,
                    SamlIdentityProviderConfigSelector idpConfigSelector,
                    Collection<SamlAssertionConsumerConfig> acsConfigs,
                    Collection<SamlEndpoint> sloEndpoints,
                    SamlRequestIdManager requestIdManager,
                    SamlSingleSignOnHandler ssoHandler,
                    SamlSingleLogoutHandler sloHandler) {
    this.authorizer = requireNonNull(authorizer, "authorizer");
    this.entityId = requireNonNull(entityId, "entityId");
    this.hostname = hostname;
    this.signingCredential = requireNonNull(signingCredential, "signingCredential");
    this.encryptionCredential = requireNonNull(encryptionCredential, "encryptionCredential");
    this.signatureAlgorithm = requireNonNull(signatureAlgorithm, "signatureAlgorithm");
    this.portConfigAutoFiller = requireNonNull(portConfigAutoFiller, "portConfigAutoFiller");
    metadataRoute = Route.builder().exact(requireNonNull(metadataPath, "metadataPath")).build();
    this.idpConfigs = ImmutableMap.copyOf(requireNonNull(idpConfigs, "idpConfigs"));
    this.defaultIdpConfig = defaultIdpConfig;
    this.idpConfigSelector = requireNonNull(idpConfigSelector, "idpConfigSelector");
    this.acsConfigs = ImmutableList.copyOf(requireNonNull(acsConfigs, "acsConfigs"));
    this.sloEndpoints = ImmutableList.copyOf(requireNonNull(sloEndpoints, "sloEndpoints"));
    this.requestIdManager = requireNonNull(requestIdManager, "requestIdManager");
    this.ssoHandler = requireNonNull(ssoHandler, "ssoHandler");
    this.sloHandler = requireNonNull(sloHandler, "sloHandler");

    defaultAcsConfig = acsConfigs.stream().filter(SamlAssertionConsumerConfig::isDefault).findFirst()
                                 .orElseThrow(() -> new IllegalArgumentException(
                                         "no default assertion consumer config"));
}
 
Example #12
Source File: HttpRedirectBindingUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a redirected URL which includes a deflated base64 string that is converted from the specified
 * {@link SAMLObject}. The URL must contain a signature of the generated query string.
 */
static String toRedirectionUrl(SAMLObject msg,
                               String endpointUrl,
                               String messageParamName,
                               Credential signingCredential,
                               String signatureAlgorithm,
                               @Nullable String relayState) {
    requireNonNull(msg, "msg");
    requireNonNull(endpointUrl, "endpointUrl");
    requireNonNull(messageParamName, "messageParamName");
    requireNonNull(signingCredential, "signingCredential");
    requireNonNull(signatureAlgorithm, "signatureAlgorithm");

    final QueryParamsBuilder params = QueryParams.builder();
    params.add(messageParamName, toDeflatedBase64(msg));

    if (relayState != null) {
        // RelayState data MAY be included with a SAML protocol message transmitted with this binding.
        // The value MUST NOT exceed 80 bytes in length and SHOULD be integrity protected by the entity
        // creating the message independent of any other protections that may or may not exist
        // during message transmission.
        if (relayState.length() > 80) {
            throw new IllegalArgumentException("too long relayState string: " + relayState.length());
        }
        params.add(RELAY_STATE, relayState);
    }

    params.add(SIGNATURE_ALGORITHM, signatureAlgorithm);

    // Use URL-encoded query string as input.
    final String input = params.toQueryString();
    final String output = generateSignature(signingCredential, signatureAlgorithm, input);
    params.add(SIGNATURE, output);

    return endpointUrl + '?' + params.toQueryString();
}
 
Example #13
Source File: HttpRedirectBindingUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signature of the specified {@code input}.
 */
@VisibleForTesting
static String generateSignature(Credential signingCredential, String algorithmURI, String input) {
    try {
        final byte[] signature =
                XMLSigningUtil.signWithURI(signingCredential, algorithmURI,
                                           input.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(signature);
    } catch (SecurityException e) {
        throw new SamlException("failed to generate a signature", e);
    }
}
 
Example #14
Source File: HttpPostBindingUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Signs the specified {@link SignableSAMLObject} with the specified {@link Credential} and
 * {@code signatureAlgorithm}, and then encodes the object into a base64 string.
 */
static String toSignedBase64(SignableSAMLObject signableObj,
                             Credential signingCredential,
                             String signatureAlgorithm) {
    sign(signableObj, signingCredential, signatureAlgorithm);
    final String messageStr = nodeToString(serialize(signableObj));
    return Base64.getEncoder().encodeToString(messageStr.getBytes(StandardCharsets.UTF_8));
}
 
Example #15
Source File: MatchingAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenAssertionSignedByUnknownKey() throws Exception {
    expectedException.expect(SamlTransformationErrorException.class);
    expectedException.expectMessage("SAML Validation Specification: Signature was not valid.");

    Credential unknownSigningCredential = new TestCredentialFactory(TEST_PUBLIC_CERT, TEST_PRIVATE_KEY).getSigningCredential();
    msaAssertionTranslator.translateSuccessResponse(Collections.singletonList(
        anAssertionWith("some-pid", LEVEL_2_AUTHN_CTX)
            .withSignature(aSignature().withSigningCredential(unknownSigningCredential).build())
            .buildUnencrypted()),
        IN_RESPONSE_TO,
        LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );
}
 
Example #16
Source File: SamlServiceProviderBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Credential apply(String keyName) {
    final CriteriaSet cs = new CriteriaSet();
    cs.add(new EntityIdCriterion(keyName));
    try {
        return resolver.resolveSingle(cs);
    } catch (Throwable cause) {
        return Exceptions.throwUnsafely(cause);
    }
}
 
Example #17
Source File: SamlMetadataServiceFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
SamlMetadataServiceFunction(String entityId,
                            Credential signingCredential,
                            Credential encryptionCredential,
                            Map<String, SamlIdentityProviderConfig> idpConfigs,
                            Collection<SamlAssertionConsumerConfig> assertionConsumerConfigs,
                            Collection<SamlEndpoint> singleLogoutEndpoints) {
    this.entityId = entityId;
    this.signingCredential = signingCredential;
    this.encryptionCredential = encryptionCredential;
    this.idpConfigs = idpConfigs;
    this.assertionConsumerConfigs = assertionConsumerConfigs;
    this.singleLogoutEndpoints = singleLogoutEndpoints;
}
 
Example #18
Source File: SamlServiceProvider.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * A {@link Credential} for signing SAML messages.
 */
Credential signingCredential() {
    return signingCredential;
}
 
Example #19
Source File: SamlIdentityProviderConfig.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a {@link Credential} of the identity provider for encryption.
 */
public Credential encryptionCredential() {
    return encryptionCredential;
}
 
Example #20
Source File: SPCredentials.java    From OpenSAML-ref-project-demo-v3 with Apache License 2.0 4 votes vote down vote up
public static Credential getCredential() {
    return credential;
}
 
Example #21
Source File: SamlServiceProvider.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * A {@link Credential} for encrypting SAML messages.
 */
Credential encryptionCredential() {
    return encryptionCredential;
}
 
Example #22
Source File: SAML2SPLoader.java    From syncope with Apache License 2.0 4 votes vote down vote up
public Credential getCredential() {
    return credential;
}
 
Example #23
Source File: X509CredentialImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public Class<? extends Credential> getCredentialType() {
    // TODO Auto-generated method stub
    return null;
}
 
Example #24
Source File: SamlIdentityProviderConfig.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a {@link Credential} of the identity provider for signing.
 */
public Credential signingCredential() {
    return signingCredential;
}
 
Example #25
Source File: SamlClient.java    From saml-client with MIT License 4 votes vote down vote up
private static Credential getCredential(X509Certificate certificate) {
  BasicX509Credential credential = new BasicX509Credential(certificate);
  credential.setCRLs(Collections.emptyList());
  return credential;
}
 
Example #26
Source File: X509CredentialImpl.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public Class<? extends Credential> getCredentialType() {
    // TODO Auto-generated method stub
    return null;
}
 
Example #27
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
private Credential getIdpVerificationCert(){
    return this.idpVerificationCert;
}
 
Example #28
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
private Credential getSpKeypair(){
    return this.spKeypair;
}
 
Example #29
Source File: MatchingAssertionTranslatorTest.java    From verify-service-provider with MIT License 4 votes vote down vote up
private Credential createMSSigningCredential() {
    Credential signingCredential = new TestCredentialFactory(TEST_RP_MS_PUBLIC_SIGNING_CERT, TEST_RP_MS_PRIVATE_SIGNING_KEY).getSigningCredential();
    ((BasicCredential) signingCredential).setEntityId(TestEntityIds.TEST_RP_MS);
    return signingCredential;
}
 
Example #30
Source File: ResponseServiceTest.java    From verify-service-provider with MIT License 4 votes vote down vote up
private Response signResponse(ResponseBuilder responseBuilder, Credential signingCredential) throws MarshallingException, SignatureException {
    return responseBuilder
        .withSigningCredential(signingCredential).build();
}