Search in sources :

Example 1 with EntityIDCriteria

use of org.opensaml.xml.security.criteria.EntityIDCriteria in project entcore by opendigitaleducation.

the class SamlValidator method validateSignature.

public boolean validateSignature(String assertion) throws Exception {
    final Response response = SamlUtils.unmarshallResponse(assertion);
    final SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
    Signature signature = response.getSignature();
    if (signature == null) {
        if (response.getAssertions() != null && !response.getAssertions().isEmpty()) {
            for (Assertion a : response.getAssertions()) {
                signature = a.getSignature();
            }
        } else if (response.getEncryptedAssertions() != null && !response.getEncryptedAssertions().isEmpty()) {
            Assertion a = decryptAssertion(response);
            if (a != null) {
                signature = a.getSignature();
            }
        } else {
            logger.error("Assertions not founds.");
            throw new ValidationException("Assertions not founds.");
        }
    }
    if (signature == null) {
        logger.error("Signature not found.");
        throw new ValidationException("Signature not found.");
    }
    profileValidator.validate(signature);
    SignatureTrustEngine sigTrustEngine = getSignatureTrustEngine(response);
    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(SamlUtils.getIssuer(response)));
    criteriaSet.add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    return sigTrustEngine.validate(signature, criteriaSet);
}
Also used : EntityIDCriteria(org.opensaml.xml.security.criteria.EntityIDCriteria) ValidationException(org.opensaml.xml.validation.ValidationException) MetadataCriteria(org.opensaml.security.MetadataCriteria) ExplicitKeySignatureTrustEngine(org.opensaml.xml.signature.impl.ExplicitKeySignatureTrustEngine) SignatureTrustEngine(org.opensaml.xml.signature.SignatureTrustEngine) UsageCriteria(org.opensaml.xml.security.criteria.UsageCriteria) SAMLSignatureProfileValidator(org.opensaml.security.SAMLSignatureProfileValidator) Signature(org.opensaml.xml.signature.Signature) CriteriaSet(org.opensaml.xml.security.CriteriaSet)

Example 2 with EntityIDCriteria

use of org.opensaml.xml.security.criteria.EntityIDCriteria in project MaxKey by dromara.

the class SamlMetadataEndpoint method metadata.

@Operation(summary = "SAML 2.0 元数据接口", description = "参数mxk_metadata_APPID", method = "GET")
@RequestMapping(value = "/" + WebConstants.MXK_METADATA_PREFIX + "{appid}.xml", produces = "application/xml", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public String metadata(HttpServletRequest request, HttpServletResponse response, @PathVariable("appid") String appId) {
    response.setContentType(ContentType.APPLICATION_XML_UTF8);
    if (signingCredential == null) {
        TrustResolver trustResolver = new TrustResolver();
        CredentialResolver credentialResolver = (CredentialResolver) trustResolver.buildKeyStoreCredentialResolver(keyStoreLoader.getKeyStore(), keyStoreLoader.getEntityName(), keyStoreLoader.getKeystorePassword());
        CriteriaSet criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName()));
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
        try {
            signingCredential = credentialResolver.resolveSingle(criteriaSet);
        } catch (SecurityException e) {
            logger.error("Credential Resolver error .", e);
        }
    }
    Validate.notNull(signingCredential);
    try {
        MetadataGenerator metadataGenerator = new MetadataGenerator();
        IDPSSODescriptor descriptor = metadataGenerator.buildIDPSSODescriptor();
        descriptor.getSingleSignOnServices().add(metadataGenerator.getSingleSignOnService(WebContext.getHttpContextPath() + "/authz/saml20/" + appId, null));
        descriptor.getSingleSignOnServices().add(metadataGenerator.getSingleSignOnService(WebContext.getHttpContextPath() + "/authz/saml20/" + appId, SAMLConstants.SAML2_REDIRECT_BINDING_URI));
        descriptor.getSingleSignOnServices().add(metadataGenerator.getSingleSignOnService(WebContext.getHttpContextPath() + "/authz/saml20/" + appId, SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI));
        descriptor.getSingleLogoutServices().add(metadataGenerator.getSingleLogoutService(WebContext.getHttpContextPath() + "/logout", null));
        descriptor.getManageNameIDServices().add(metadataGenerator.getManageNameIDService(WebContext.getHttpContextPath() + "/saml/metadata/" + WebConstants.MXK_METADATA_PREFIX + appId + ".xml"));
        descriptor.getKeyDescriptors().add(metadataGenerator.generateEncryptionKeyDescriptor(signingCredential));
        descriptor.getKeyDescriptors().add(metadataGenerator.generateSignKeyDescriptor(signingCredential));
        descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.TRANSIENT));
        descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.PERSISTENT));
        descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.EMAIL));
        descriptor.getNameIDFormats().add(metadataGenerator.generateNameIDFormat(NameIDType.ENTITY));
        ContactPersonTypeEnumeration contactPersonType = null;
        if (saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.ADMINISTRATIVE)) {
            contactPersonType = ContactPersonTypeEnumeration.ADMINISTRATIVE;
        } else if (saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.TECHNICAL)) {
            contactPersonType = ContactPersonTypeEnumeration.TECHNICAL;
        } else if (saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.BILLING)) {
            contactPersonType = ContactPersonTypeEnumeration.BILLING;
        } else if (saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.SUPPORT)) {
            contactPersonType = ContactPersonTypeEnumeration.SUPPORT;
        } else if (saml20Metadata.getContactType().equalsIgnoreCase(Saml20Metadata.ContactPersonType.OTHER)) {
            contactPersonType = ContactPersonTypeEnumeration.OTHER;
        }
        descriptor.getContactPersons().add(metadataGenerator.getContactPerson(saml20Metadata.getCompany(), saml20Metadata.getGivenName(), saml20Metadata.getSurName(), saml20Metadata.getEmailAddress(), saml20Metadata.getTelephoneNumber(), contactPersonType));
        descriptor.setOrganization(metadataGenerator.getOrganization(saml20Metadata.getOrgName(), saml20Metadata.getOrgDisplayName(), saml20Metadata.getOrgURL()));
        EntityDescriptor entityDescriptor = metadataGenerator.buildEntityDescriptor(issuerEntityName, descriptor);
        String entityDescriptorXml = XMLHelper.prettyPrintXML(metadataGenerator.marshallerMetadata(entityDescriptor));
        logger.trace("EntityDescriptor element XML : \\n");
        logger.trace(entityDescriptorXml);
        return entityDescriptorXml;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
}
Also used : EntityDescriptor(org.opensaml.saml2.metadata.EntityDescriptor) EntityIDCriteria(org.opensaml.xml.security.criteria.EntityIDCriteria) IDPSSODescriptor(org.opensaml.saml2.metadata.IDPSSODescriptor) UsageCriteria(org.opensaml.xml.security.criteria.UsageCriteria) CriteriaSet(org.opensaml.xml.security.CriteriaSet) ContactPersonTypeEnumeration(org.opensaml.saml2.metadata.ContactPersonTypeEnumeration) SecurityException(org.opensaml.xml.security.SecurityException) MetadataGenerator(org.maxkey.authz.saml20.metadata.MetadataGenerator) CredentialResolver(org.opensaml.xml.security.credential.CredentialResolver) SecurityException(org.opensaml.xml.security.SecurityException) TrustResolver(org.maxkey.authz.saml.common.TrustResolver) Operation(io.swagger.v3.oas.annotations.Operation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with EntityIDCriteria

use of org.opensaml.xml.security.criteria.EntityIDCriteria in project MaxKey by dromara.

the class PostBindingAdapter method buildSPSigningCredential.

public Credential buildSPSigningCredential() throws Exception {
    KeyStore trustKeyStore = KeyStoreUtil.bytes2KeyStore(getSaml20Details().getKeyStore(), getKeyStoreLoader().getKeyStore().getType(), getKeyStoreLoader().getKeystorePassword());
    TrustResolver trustResolver = new TrustResolver();
    KeyStoreCredentialResolver credentialResolver = trustResolver.buildKeyStoreCredentialResolver(trustKeyStore, getSaml20Details().getEntityId(), getKeyStoreLoader().getKeystorePassword());
    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(getSaml20Details().getEntityId()));
    criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
    try {
        spSigningCredential = credentialResolver.resolveSingle(criteriaSet);
    } catch (SecurityException e) {
        logger.error("Credential Resolver error . ", e);
        throw new Exception(e);
    }
    Validate.notNull(spSigningCredential);
    return spSigningCredential;
}
Also used : EntityIDCriteria(org.opensaml.xml.security.criteria.EntityIDCriteria) UsageCriteria(org.opensaml.xml.security.criteria.UsageCriteria) CriteriaSet(org.opensaml.xml.security.CriteriaSet) SecurityException(org.opensaml.xml.security.SecurityException) KeyStoreCredentialResolver(org.opensaml.xml.security.credential.KeyStoreCredentialResolver) KeyStore(java.security.KeyStore) MessageEncodingException(org.opensaml.ws.message.encoder.MessageEncodingException) SecurityException(org.opensaml.xml.security.SecurityException) TrustResolver(org.maxkey.authz.saml.common.TrustResolver)

Example 4 with EntityIDCriteria

use of org.opensaml.xml.security.criteria.EntityIDCriteria in project MaxKey by dromara.

the class ConsumerEndpoint method initCredential.

/**
 * 初始化sp证书
 *
 * @throws Exception
 */
private void initCredential(String spId) throws Exception {
    // 1. 获取 sp keyStore
    AppsSAML20Details saml20Details = saml20DetailsService.get(spId);
    if (saml20Details == null) {
        logger.error("spid[" + spId + "] not exists");
        throw new Exception();
    }
    byte[] keyStoreBytes = saml20Details.getKeyStore();
    InputStream keyStoreStream = new ByteArrayInputStream(keyStoreBytes);
    try {
        KeyStore keyStore = KeyStore.getInstance(keyStoreLoader.getKeystoreType());
        keyStore.load(keyStoreStream, keyStoreLoader.getKeystorePassword().toCharArray());
        Map<String, String> passwords = new HashMap<String, String>();
        for (Enumeration<String> en = keyStore.aliases(); en.hasMoreElements(); ) {
            String aliase = en.nextElement();
            if (aliase.equalsIgnoreCase(keyStoreLoader.getEntityName())) {
                passwords.put(aliase, keyStoreLoader.getKeystorePassword());
            }
        }
        // TrustResolver trustResolver = new
        // TrustResolver(keyStore,keyStoreLoader.getIdpIssuingEntityName(),keyStoreLoader.getKeystorePassword());
        AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(keyStoreLoader.getEntityName(), timeService, idService);
        // endpointGenerator = new EndpointGenerator();
        CriteriaSet criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIDCriteria(keyStoreLoader.getEntityName()));
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
        KeyStoreCredentialResolver credentialResolver = new KeyStoreCredentialResolver(keyStore, passwords);
        signingCredential = credentialResolver.resolveSingle(criteriaSet);
        Validate.notNull(signingCredential);
        // adapter set resolver
        TrustResolver trustResolver = new TrustResolver(keyStore, keyStoreLoader.getEntityName(), keyStoreLoader.getKeystorePassword(), issueInstantRule, messageReplayRule, "POST");
        extractBindingAdapter.setSecurityPolicyResolver(trustResolver.getStaticSecurityPolicyResolver());
    } catch (Exception e) {
        logger.error("初始化sp证书出错");
        throw new Exception(e);
    }
}
Also used : AppsSAML20Details(org.maxkey.entity.apps.AppsSAML20Details) AuthnResponseGenerator(org.maxkey.authz.saml20.provider.xml.AuthnResponseGenerator) EntityIDCriteria(org.opensaml.xml.security.criteria.EntityIDCriteria) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) KeyStore(java.security.KeyStore) MessageDecodingException(org.opensaml.ws.message.decoder.MessageDecodingException) IdentityProviderAuthenticationException(org.maxkey.authz.saml20.consumer.spring.IdentityProviderAuthenticationException) ValidationException(org.opensaml.xml.validation.ValidationException) SecurityException(org.opensaml.xml.security.SecurityException) ServiceProviderAuthenticationException(org.maxkey.authz.saml20.consumer.spring.ServiceProviderAuthenticationException) ByteArrayInputStream(java.io.ByteArrayInputStream) UsageCriteria(org.opensaml.xml.security.criteria.UsageCriteria) CriteriaSet(org.opensaml.xml.security.CriteriaSet) KeyStoreCredentialResolver(org.opensaml.xml.security.credential.KeyStoreCredentialResolver) TrustResolver(org.maxkey.authz.saml.common.TrustResolver)

Example 5 with EntityIDCriteria

use of org.opensaml.xml.security.criteria.EntityIDCriteria in project MaxKey by dromara.

the class MetadataGenerator method samlmtest.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void samlmtest() {
    try {
        KeyStoreLoader keyStoreLoader = new KeyStoreLoader();
        keyStoreLoader.setKeystorePassword("secret");
        keyStoreLoader.setKeystoreFile(new FileSystemResource("D:/JavaIDE/cert/idp-keystore.jks"));
        keyStoreLoader.afterPropertiesSet();
        KeyStore trustKeyStore = keyStoreLoader.getKeyStore();
        IssueInstantRule issueInstantRule = new IssueInstantRule(90, 300);
        ReplayCache replayCache = new ReplayCache(new MapBasedStorageService(), 14400000);
        MessageReplayRule messageReplayRule = new MessageReplayRule(replayCache);
        TrustResolver trustResolver = new TrustResolver(trustKeyStore, "idp", keyStoreLoader.getKeystorePassword(), issueInstantRule, messageReplayRule, "POST");
        CredentialResolver credentialResolver = (CredentialResolver) trustResolver.getKeyStoreCredentialResolver();
        CriteriaSet criteriaSet = new CriteriaSet();
        criteriaSet.add(new EntityIDCriteria("idp"));
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
        Credential signingCredential = null;
        try {
            signingCredential = credentialResolver.resolveSingle(criteriaSet);
        } catch (SecurityException e) {
            System.out.println("Credential resolve error : " + e);
            throw new Exception(e);
        }
        IDPSSODescriptor descriptor = buildIDPSSODescriptor();
        descriptor.getSingleSignOnServices().add(getSingleSignOnService("http://sso.maxkey.org/sso", null));
        descriptor.getSingleSignOnServices().add(getSingleSignOnService("http://sso.maxkey.org/sso", SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI));
        descriptor.getSingleLogoutServices().add(getSingleLogoutService("http://sso.maxkey.org/slo", null));
        descriptor.getKeyDescriptors().add(generateEncryptionKeyDescriptor(signingCredential));
        descriptor.getKeyDescriptors().add(generateSignKeyDescriptor(signingCredential));
        descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.TRANSIENT));
        descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.PERSISTENT));
        descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.EMAIL));
        descriptor.getNameIDFormats().add(generateNameIDFormat(NameIDType.ENTITY));
        descriptor.getContactPersons().add(getContactPerson("maxkey", "shi", "ming", "shimingxy@163.com", "18724229876", null));
        descriptor.setOrganization(getOrganization("maxkey", "maxkey", "http://sso.maxkey.org"));
        String entityId = "http://www.test.com";
        EntityDescriptor entityDescriptor = buildEntityDescriptor(entityId, descriptor);
        String descriptorelementxml = XMLHelper.prettyPrintXML(marshallerMetadata(entityDescriptor));
        System.out.println("descriptor elementxm:\\n");
        System.out.println(descriptorelementxml);
        logger.info(descriptorelementxml);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : EntityIDCriteria(org.opensaml.xml.security.criteria.EntityIDCriteria) Credential(org.opensaml.xml.security.credential.Credential) KeyStoreLoader(org.maxkey.crypto.keystore.KeyStoreLoader) MapBasedStorageService(org.opensaml.util.storage.MapBasedStorageService) IDPSSODescriptor(org.opensaml.saml2.metadata.IDPSSODescriptor) ReplayCache(org.opensaml.util.storage.ReplayCache) SecurityException(org.opensaml.xml.security.SecurityException) FileSystemResource(org.springframework.core.io.FileSystemResource) LocalizedString(org.opensaml.saml2.metadata.LocalizedString) KeyStore(java.security.KeyStore) IssueInstantRule(org.opensaml.common.binding.security.IssueInstantRule) SecurityException(org.opensaml.xml.security.SecurityException) UnmarshallingException(org.opensaml.xml.io.UnmarshallingException) ConfigurationException(org.opensaml.xml.ConfigurationException) EntityDescriptor(org.opensaml.saml2.metadata.EntityDescriptor) UsageCriteria(org.opensaml.xml.security.criteria.UsageCriteria) CriteriaSet(org.opensaml.xml.security.CriteriaSet) MessageReplayRule(org.opensaml.common.binding.security.MessageReplayRule) CredentialResolver(org.opensaml.xml.security.credential.CredentialResolver) TrustResolver(org.maxkey.authz.saml.common.TrustResolver)

Aggregations

CriteriaSet (org.opensaml.xml.security.CriteriaSet)8 EntityIDCriteria (org.opensaml.xml.security.criteria.EntityIDCriteria)8 UsageCriteria (org.opensaml.xml.security.criteria.UsageCriteria)8 SecurityException (org.opensaml.xml.security.SecurityException)7 TrustResolver (org.maxkey.authz.saml.common.TrustResolver)4 KeyStore (java.security.KeyStore)3 ValidationException (org.opensaml.xml.validation.ValidationException)3 IdentityProviderAuthenticationException (org.maxkey.authz.saml20.consumer.spring.IdentityProviderAuthenticationException)2 ServiceProviderAuthenticationException (org.maxkey.authz.saml20.consumer.spring.ServiceProviderAuthenticationException)2 EntityDescriptor (org.opensaml.saml2.metadata.EntityDescriptor)2 IDPSSODescriptor (org.opensaml.saml2.metadata.IDPSSODescriptor)2 MessageDecodingException (org.opensaml.ws.message.decoder.MessageDecodingException)2 MessageEncodingException (org.opensaml.ws.message.encoder.MessageEncodingException)2 CredentialResolver (org.opensaml.xml.security.credential.CredentialResolver)2 KeyStoreCredentialResolver (org.opensaml.xml.security.credential.KeyStoreCredentialResolver)2 Operation (io.swagger.v3.oas.annotations.Operation)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 HashMap (java.util.HashMap)1 EndpointGenerator (org.maxkey.authz.saml.common.EndpointGenerator)1