Beispiel #1
0
    def __init__(self):

        credential = self.get_default_credential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex
Beispiel #2
0
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex
 def __init__(self, credential: ChainedTokenCredential, options: Options):
     self.options = options
     self._cert_client = CertificateClient(options.azure_keyvault_uri,
                                           credential)
     self._dns_client = DnsManagementClient(credential,
                                            options.azure_subscription_id)
     blob_svc_client = BlobServiceClient.from_connection_string(
         options.cert_request_connection_str, )
     self._container_client = blob_svc_client.get_container_client(
         options.cert_request_container)
    def __init__(self, arguments):
        super().__init__(arguments)

        # Auth configuration
        self.credential = EnvironmentCredential()
        self.async_credential = AsyncEnvironmentCredential()

        # Create clients
        vault_url = self.get_from_env("AZURE_KEYVAULT_URL")
        self.client = CertificateClient(vault_url, self.credential)
        self.async_client = AsyncCertificateClient(vault_url,
                                                   self.async_credential)
Beispiel #5
0
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        authority_host = os.environ.get('AZURE_AUTHORITY_HOST') or KnownAuthorities.AZURE_PUBLIC_CLOUD
        credential = DefaultAzureCredential(authority=authority_host)
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential
        )

        self.certificate_name = "cert-name-" + uuid.uuid1().hex
Beispiel #6
0
    def __init__(self, arguments):
        super().__init__(arguments)

        # Auth configuration
        self.credential = DefaultAzureCredential()
        self.async_credential = AsyncDefaultAzureCredential()

        # Create clients
        vault_url = self.get_from_env("AZURE_KEYVAULT_URL")
        self.client = CertificateClient(vault_url, self.credential, **self._client_kwargs)
        self.async_client = AsyncCertificateClient(vault_url, self.async_credential, **self._client_kwargs)
        self.certificate_name = "livekvtestgetcertperfcert"
def main():
    try:

        # Enable logging
        enable_logging()

        # Setup some sample data
        sample_data = {
            "value1": "some value 1",
            "value2": "some value 2",
            "value3": "some value 3",
            "value4": "some value 4"
        }

        # Convert the dict to string, encode to bytes, and hash the data
        sample_data_hash = hashlib.sha512(
            json.dumps(sample_data).encode('UTF-8')).digest()

        # Obtain a credential from the system-assigned managed identity
        msi_credential = DefaultAzureCredential()

        # Get the key from Key Vault and setup a cryptography client
        key_client = KeyClient(KEY_VAULT_URL, msi_credential)
        key = key_client.get_key(CERTIFICATE_NAME)
        crypto_client = CryptographyClient(key, credential=msi_credential)

        # Use Key Vault to calculate a signature using RSASSA-PKCS1-v1_5 using SHA-512
        data_signature = (crypto_client.sign(SignatureAlgorithm.rs512,
                                             sample_data_hash)).signature

        # Retrieve the certificate from Key Vault
        cert_client = CertificateClient(KEY_VAULT_URL, msi_credential)
        result = (cert_client.get_certificate(CERTIFICATE_NAME)).cer

        # Load the DER certificate returned into an x509 object and get the public key
        cert = load_der_x509_certificate(result, backend=default_backend())
        public_key = cert.public_key()

        # Verify the signature
        try:
            public_key.verify(signature=data_signature,
                              data=(json.dumps(sample_data)).encode('UTF-8'),
                              padding=padding.PKCS1v15(),
                              algorithm=hashes.SHA512())
            logging.info('Payload verified successfully')
            print('Payload verified successfully!')

        except InvalidSignature:
            print('Payload and/or signature files failed verification')

    except Exception:
        logging.error('Execution error: ', exc_info=True)
Beispiel #8
0
class KeyVaultCertificates:
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        authority_host = os.environ.get('AZURE_AUTHORITY_HOST') or KnownAuthorities.AZURE_PUBLIC_CLOUD
        credential = DefaultAzureCredential(authority=authority_host)
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential
        )

        self.certificate_name = "cert-name-" + uuid.uuid1().hex

    def create_certificate(self):
        print("Creating certificate (name: {})".format(self.certificate_name))
        create_poller = self.certificate_client.begin_create_certificate(
            certificate_name=self.certificate_name,
            policy=CertificatePolicy.get_default())
        print("\twaiting...")
        create_poller.result()
        print("\tdone")

    def get_certificate(self):
        print("Getting a certificate...")
        certificate = self.certificate_client.get_certificate(certificate_name=self.certificate_name)
        print("\tdone, certificate: {}.".format(certificate.name))

    def delete_certificate(self):
        print("Deleting a certificate...")
        poller = self.certificate_client.begin_delete_certificate(certificate_name=self.certificate_name)
        deleted_certificate = poller.result()
        print("\tdone: " + deleted_certificate.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Certificates\nIdentity - Credential")
        print("------------------------")
        print("1) Create a certificate")
        print("2) Get that certificate")
        print("3) Delete that certificate (Clean up the resource)")
        print("")

        try:
            self.create_certificate()
            self.get_certificate()
        finally:
            self.delete_certificate()
def get_certdate():

    credential = DefaultAzureCredential()
    certificate_client = CertificateClient(vault_url=(os.environ.get('kvurl')),
                                           credential=credential)
    certificate = certificate_client.get_certificate(
        certificate_name=(os.environ.get('certname')))
    cert_date = certificate.properties.expires_on.strftime("%d/%m/%Y")
    limit_date = (datetime.now() + timedelta(days=7)).strftime("%d/%m/%Y")
    slack_token = os.environ.get('slacktoken')

    if cert_date == limit_date:
        queue_build()
        slack_message('O certificate vai expirar')
    else:
        slack_message('O certificate não vai expirar')
Beispiel #10
0
class KeyVaultCertificates(KeyVaultBase):
    def __init__(self):

        credential = self.get_default_credential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex

    def create_certificate(self):
        print("Creating certificate (name: {})".format(self.certificate_name))
        create_poller = self.certificate_client.begin_create_certificate(
            certificate_name=self.certificate_name,
            policy=CertificatePolicy.get_default())
        print("\twaiting...")
        create_poller.result()
        print("\tdone")

    def get_certificate(self):
        print("Getting a certificate...")
        certificate = self.certificate_client.get_certificate(
            certificate_name=self.certificate_name)
        print("\tdone, certificate: {}.".format(certificate.name))

    def delete_certificate(self):
        print("Deleting a certificate...")
        poller = self.certificate_client.begin_delete_certificate(
            certificate_name=self.certificate_name)
        deleted_certificate = poller.result()
        print("\tdone: " + deleted_certificate.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Certificates\nIdentity - Credential")
        print("------------------------")
        print("1) Create a certificate")
        print("2) Get that certificate")
        print("3) Delete that certificate (Clean up the resource)")
        print("")

        try:
            self.create_certificate()
            self.get_certificate()
        finally:
            self.delete_certificate()
def test_unsupported_version():
    """When given an unsupported API version, the client should raise an error listing supported versions"""

    with pytest.raises(NotImplementedError) as ex:
        client = CertificateClient("https://localhost",
                                   credential=object(),
                                   api_version="nonsense")
    assert all(version.value in str(ex.value) for version in ApiVersion)
def test_context_manager():
    transport = mock.MagicMock()
    client = CertificateClient(vault_url="https://localhost", credential=object(), transport=transport)

    with client:
        assert transport.__enter__.call_count == 1
    assert transport.__enter__.call_count == 1
    assert transport.__exit__.call_count == 1
Beispiel #13
0
def test_service_headers_allowed_in_logs():
    service_headers = {
        "x-ms-keyvault-network-info", "x-ms-keyvault-region",
        "x-ms-keyvault-service-version"
    }
    client = CertificateClient("...", object())
    assert service_headers.issubset(
        client._client._config.http_logging_policy.allowed_header_names)
Beispiel #14
0
class KeyVaultCertificates:
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.certificate_client = CertificateClient(
            vault_url=os.environ["AZURE_PROJECT_URL"], credential=credential)

        self.certificate_name = "cert-name-" + uuid.uuid1().hex

    def create_certificate(self):
        self.certificate_client.begin_create_certificate(
            name=self.certificate_name,
            policy=CertificatePolicy.get_default()).wait()
        print("\tdone")

    def get_certificate(self):
        print("Getting a certificate...")
        certificate = self.certificate_client.get_certificate(
            name=self.certificate_name)
        print(f"\tdone, certificate: {certificate.name}.")

    def delete_certificate(self):
        print("Deleting a certificate...")
        deleted_certificate = self.certificate_client.delete_certificate(
            name=self.certificate_name)
        print("\tdone: " + deleted_certificate.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Certificates\nIdentity - Credential")
        print("------------------------")
        print("1) Create a certificate")
        print("2) Get that certificate")
        print("3) Delete that certificate (Clean up the resource)")
        print("")

        try:
            self.create_certificate()
            self.get_certificate()
        finally:
            self.delete_certificate()
Beispiel #15
0
def test_custom_hook_policy():
    class CustomHookPolicy(SansIOHTTPPolicy):
        pass

    client = CertificateClient("...",
                               object(),
                               custom_hook_policy=CustomHookPolicy())
    assert isinstance(client._client._config.custom_hook_policy,
                      CustomHookPolicy)
Beispiel #16
0
    def backup_restore_certificate(self):
        """
        backs up a key vault certificate and restores it to another key vault
        """
        # create a key vault
        first_vault = self.create_vault()

        # create a certificate client
        credential = DefaultAzureCredential()
        first_certificate_client = CertificateClient(
            vault_url=first_vault.properties.vault_uri, credential=credential)

        # add a certificate to the vault
        certificate_name = get_name('certificate')

        certificate = first_certificate_client.begin_create_certificate(
            certificate_name, CertificatePolicy.get_default()).result()
        print('created certificate {}'.format(certificate.name))

        # list the certificates in the vault
        certificate_properties = first_certificate_client.list_properties_of_certificates(
        )
        print("all of the certificates in the client's vault:")
        for certificate_property in certificate_properties:
            print(certificate_property.name)

        # backup the certificate
        backup = first_certificate_client.backup_certificate(certificate_name)
        print('backed up certificate {}'.format(certificate_name))

        # create a second vault
        second_vault = self.create_vault()

        # create a certificate client
        second_certificate_client = CertificateClient(
            vault_url=second_vault.properties.vault_uri, credential=credential)

        # restore the certificate to the new vault
        restored = second_certificate_client.restore_certificate_backup(backup)
        print('restored certificate {}'.format(restored.name))

        # list the certificates in the new vault
        certificate_properties = second_certificate_client.list_properties_of_certificates(
        )
        print("all of the certificates in the new vault:")
        for certificate_property in certificate_properties:
            print(certificate_property.name)
Beispiel #17
0
def test_create_certificate_client():
    vault_url = "vault_url"
    # pylint:disable=unused-variable
    # [START create_certificate_client]

    from azure.identity import DefaultAzureCredential
    from azure.keyvault.certificates import CertificateClient

    # Create a CertificateClient using default Azure credentials
    credential = DefaultAzureCredential()
    certificate_client = CertificateClient(vault_url, credential)
class GetCertificateTest(PerfStressTest):
    def __init__(self, arguments):
        super().__init__(arguments)

        # Auth configuration
        self.credential = EnvironmentCredential()
        self.async_credential = AsyncEnvironmentCredential()

        # Create clients
        vault_url = self.get_from_env("AZURE_KEYVAULT_URL")
        self.client = CertificateClient(vault_url, self.credential)
        self.async_client = AsyncCertificateClient(vault_url,
                                                   self.async_credential)

    async def global_setup(self):
        """The global setup is run only once."""
        await super().global_setup()
        await self.async_client.create_certificate(
            "livekvtestperfcert", CertificatePolicy.get_default())

    async def global_cleanup(self):
        """The global cleanup is run only once."""
        await self.async_client.delete_certificate("livekvtestperfcert")
        await self.async_client.purge_deleted_certificate("livekvtestperfcert")
        await super().global_cleanup()

    async def close(self):
        """This is run after cleanup."""
        await self.async_client.close()
        await self.async_credential.close()
        await super().close()

    def run_sync(self):
        """The synchronous perf test."""
        self.client.get_certificate("livekvtestperfcert")

    async def run_async(self):
        """The asynchronous perf test."""
        await self.async_client.get_certificate("livekvtestperfcert")
 def __init__(self,
              vault_url,
              credential,
              transport=None,
              api_version=None,
              **kwargs):
     # type: (str, TokenCredential, Optional[HttpTransport], Optional[str], **Any) -> None
     super(VaultClient, self).__init__(vault_url,
                                       credential,
                                       transport=transport,
                                       api_version=api_version,
                                       **kwargs)
     self._certificates = CertificateClient(self.vault_url,
                                            credential,
                                            generated_client=self._client,
                                            **kwargs)
Beispiel #20
0
def test_policy_expected_errors_for_create_cert():
    """Either a subject or subject alternative name property are required for creating a certificate"""
    client = CertificateClient("...", object())

    with pytest.raises(ValueError, match=NO_SAN_OR_SUBJECT):
        policy = CertificatePolicy()
        client.begin_create_certificate("...", policy=policy)

    with pytest.raises(ValueError, match=NO_SAN_OR_SUBJECT):
        policy = CertificatePolicy(issuer_name=WellKnownIssuerNames.self)
        client.begin_create_certificate("...", policy=policy)
Beispiel #21
0
 def __init__(self,
              vault_url,
              credential,
              transport=None,
              api_version=None,
              is_live=True,
              **kwargs):
     # type: (str, TokenCredential, Optional[HttpTransport], Optional[str], Optional[bool], **Any) -> None
     super(VaultClient, self).__init__(vault_url,
                                       credential,
                                       transport=transport,
                                       api_version=api_version,
                                       **kwargs)
     self._certificates = CertificateClient(self.vault_url,
                                            credential,
                                            generated_client=self._client,
                                            **kwargs)
     if not is_live:
         # ensure pollers don't sleep during playback
         for attr in dir(self._certificates):
             if attr.startswith("begin_"):
                 fn = getattr(self._certificates, attr)
                 wrapper = functools.partial(fn, _polling_interval=0)
                 setattr(self._certificates, attr, wrapper)
# 2. Backup a certificate (backup_certificate)
#
# 3. Delete a certificate (delete_certificate)
#
# 4. Purge a deleted certificate (purge_deleted_certificate)
#
# 5. Restore a certificate (restore_certificate_backup)
# ----------------------------------------------------------------------------------------------------------

# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_endpoint=VAULT_ENDPOINT,
                           credential=credential)
try:
    print("\n.. Create Certificate")
    cert_name = "BackupRestoreCertificate"

    # Let's create a certificate for your key vault.
    # if the certificate already exists in the Key Vault, then a new version of the certificate is created.
    # A long running poller is returned for the create certificate operation.
    create_certificate_poller = client.begin_create_certificate(
        name=cert_name, policy=CertificatePolicy.get_default())

    # The result call awaits the completion of the create certificate operation and returns the final result.
    # It will return a certificate if creation is successful, and will return the CertificateOperation if not.
    certificate = create_certificate_poller.result()
    print("Certificate with name '{0}' created.".format(cert_name))
Beispiel #23
0
#
# 2. Get an existing certificate (get_certificate)
#
# 3. Update an existing certificate (update_certificate)
#
# 4. Delete a certificate (begin_delete_certificate)
#
# ----------------------------------------------------------------------------------------------------------

# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_url=VAULT_URL, credential=credential)
try:
    # Let's create a certificate for holding bank account credentials valid for 1 year.
    # if the certificate already exists in the Key Vault, then a new version of the certificate is created.
    print("\n.. Create certificate")

    # Before creating your certificate, let's create the management policy for your certificate.
    # Here you specify the properties of the key, secret, and issuer backing your certificate,
    # the X509 component of your certificate, and any lifetime actions you would like to be taken
    # on your certificate

    # Alternatively, if you would like to use our default policy, use CertificatePolicy.get_default()
    cert_policy = CertificatePolicy(
        issuer_name=WellKnownIssuerNames.self,
        subject="CN=*.microsoft.com",
        san_dns_names=["sdk.azure-int.net"],
 def _get_vault_certs_client(self) -> CertificateClient:
     return CertificateClient(**self._get_client_credentials())
Beispiel #25
0
def run_example():
    """Resource Group management example."""
    #
    # Create the Resource Manager Client with an Application (service principal) token provider
    #
    subscription_id = os.environ.get(
        'AZURE_SUBSCRIPTION_ID',
        '11111111-1111-1111-1111-111111111111')  # your Azure Subscription Id
    credential = ClientSecretCredential(
        client_id=os.environ['AZURE_CLIENT_ID'],
        client_secret=os.environ['AZURE_CLIENT_SECRET'],
        tenant_id=os.environ['AZURE_TENANT_ID'])
    resource_client = ResourceManagementClient(credential, subscription_id)
    compute_client = ComputeManagementClient(credential, subscription_id)
    network_client = NetworkManagementClient(credential, subscription_id)
    kv_mgmt_client = KeyVaultManagementClient(credential, subscription_id)

    cert_client = CertificateClient(
        "https://{}.vault.azure.net".format(KV_NAME), credential)

    # Create Resource group
    print('\nCreate Resource Group')
    resource_group = resource_client.resource_groups.create_or_update(
        GROUP_NAME, {'location': LOCATION})
    print_item(resource_group)

    # Resolve the client_id as object_id for KeyVault access policy.
    # If you already know your object_id, you can skip this part
    sp_object_id = os.environ.get('AZURE_CLIENT_OBJECT_ID',
                                  '11111111-1111-1111-1111-111111111111'
                                  )  # your service principal's object id

    # Create Key Vault account
    print('\nCreate Key Vault account')
    async_vault_poller = kv_mgmt_client.vaults.begin_create_or_update(
        GROUP_NAME,
        KV_NAME,
        {
            'location': LOCATION,
            'properties': {
                'sku': {
                    'name': 'standard'
                },
                'tenant_id':
                os.environ['AZURE_TENANT_ID'],
                'access_policies': [{
                    'tenant_id': os.environ['AZURE_TENANT_ID'],
                    'object_id': sp_object_id,
                    'permissions': {
                        # Only "certificates" and "secrets" are needed for this sample
                        'certificates': ['all'],
                        'secrets': ['all']
                    }
                }],
                # Critical to allow the VM to download certificates later
                'enabled_for_deployment':
                True
            }
        })
    vault = async_vault_poller.result()
    print_item(vault)

    # # KeyVault recommentation is to wait 20 seconds after account creation for DNS update
    time.sleep(20)

    # Ask KeyVault to create a Certificate
    certificate_name = "cert1"
    print('\nCreate Key Vault Certificate')
    certificate_poller = cert_client.begin_create_certificate(
        certificate_name, policy=DEFAULT_POLICY)
    certificate_poller.wait()
    while True:
        check = cert_client.get_certificate_operation(certificate_name)
        if check.status != 'inProgress':
            break
        try:
            print("Waiting for certificate creation to finish")
            time.sleep(10)
        except KeyboardInterrupt:
            print("Certificate creation wait cancelled.")
            raise
    print_item(check)

    print('\nGet Key Vault created certificate as a secret')
    secret_client = SecretClient("https://{}.vault.azure.net".format(KV_NAME),
                                 credential)
    certificate_as_secret = secret_client.get_secret(
        certificate_name,
        ""  # Latest version
    )
    print_item(certificate_as_secret)

    print("\nCreate Network")
    # Create Network components of the VM
    # This is not related to the main topic of this sample and is just required to create the VM
    subnet = create_virtual_network(network_client)
    public_ip = create_public_ip(network_client)
    nic = create_network_interface(network_client, subnet, public_ip)
    print_item(nic)

    # Create a VM with some Key Vault certificates
    params_create = {
        'location': LOCATION,
        'hardware_profile': get_hardware_profile(),
        'network_profile': get_network_profile(nic.id),
        'storage_profile': get_storage_profile(),
        'os_profile': {
            'admin_username':
            ADMIN_LOGIN,
            'admin_password':
            ADMIN_PASSWORD,
            'computer_name':
            'testkvcertificates',
            # This is the Key Vault critical part
            'secrets': [{
                'source_vault': {
                    'id': vault.id,
                },
                'vault_certificates': [{
                    'certificate_url':
                    certificate_as_secret.id
                }]
            }]
        }
    }

    print("\nCreate VM")
    vm_poller = compute_client.virtual_machines.begin_create_or_update(
        GROUP_NAME,
        VM_NAME,
        params_create,
    )
    vm_result = vm_poller.result()
    print_item(vm_result)

    # Get the PublicIP after VM creation, since assignment is dynamic
    public_ip = network_client.public_ip_addresses.get(GROUP_NAME,
                                                       PUBLIC_IP_NAME)

    print("You can connect to the VM using:")
    print("ssh {}@{}".format(
        ADMIN_LOGIN,
        public_ip.ip_address,
    ))
    print("And password: {}\n".format(ADMIN_PASSWORD))

    print("Your certificate is available in this folder: /var/lib/waagent")
    print("You must be root to see it (sudo su)\n")

    input("Press enter to delete this Resource Group.")

    # Delete Resource group and everything in it
    print('Delete Resource Group')
    delete_async_operation = resource_client.resource_groups.begin_delete(
        GROUP_NAME)
    delete_async_operation.wait()
    print("\nDeleted: {}".format(GROUP_NAME))
# 2. Backup a certificate (backup_certificate)
#
# 3. Delete a certificate (begin_delete_certificate)
#
# 4. Purge a certificate (purge_deleted_certificate)
#
# 5. Restore a certificate (restore_certificate_backup)
# ----------------------------------------------------------------------------------------------------------

# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_url=VAULT_URL, credential=credential)

print("\n.. Create Certificate")
cert_name = "BackupRestoreCertificate"

# Let's create a certificate for your key vault.
# if the certificate already exists in the Key Vault, then a new version of the certificate is created.
# A long running poller is returned for the create certificate operation.
create_certificate_poller = client.begin_create_certificate(
    certificate_name=cert_name, policy=CertificatePolicy.get_default())

# The result call awaits the completion of the create certificate operation and returns the final result.
# It will return a certificate if creation is successful, and will return the CertificateOperation if not.
certificate = create_certificate_poller.result()
print("Certificate with name '{0}' created.".format(cert_name))
Beispiel #27
0
# 2. Backup a certificate (backup_certificate)
#
# 3. Delete a certificate (delete_certificate)
#
# 4. Purge a deleted certificate (purge_deleted_certificate)
#
# 5. Restore a certificate (restore_certificate)
# ----------------------------------------------------------------------------------------------------------

# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_endpoint=VAULT_ENDPOINT,
                           credential=credential)
try:
    print("\n.. Create Certificate")
    cert_name = "BackupRestoreCertificate"

    # Let's create a certificate for your key vault.
    # if the certificate already exists in the Key Vault, then a new version of the certificate is created.
    # A long running poller is returned for the create certificate operation.
    create_certificate_poller = client.create_certificate(name=cert_name)

    # The result call awaits the completion of the create certificate operation and returns the final result.
    # It will return a certificate if creation is successful, and will return the CertificateOperation if not.
    certificate = create_certificate_poller.result()
    print("Certificate with name '{0}' created.".format(cert_name))

    # Backups are good to have, if in case certificates gets deleted accidentally.
Beispiel #28
0
# Sample - demonstrates basic CRUD operations for the certificate contacts for a key vault.
#
# 1. Create contacts (create_contacts)
#
# 2. Get contacts (get_contacts)
#
# 3. Delete contacts (delete_contacts)
# ----------------------------------------------------------------------------------------------------------

# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_url=VAULT_URL, credential=credential)
try:
    # First we create a list of Contacts that we would like to make the certificate contacts for this key vault.
    contact_list = [
        CertificateContact(email="*****@*****.**",
                           name="John Doe",
                           phone="1111111111"),
        CertificateContact(email="*****@*****.**",
                           name="John Doe2",
                           phone="2222222222"),
    ]

    # Creates and sets the certificate contacts for this key vault.
    client.create_contacts(contact_list)

    # Gets the certificate contacts for this key vault.
#
# 2. Delete a certificate (begin_delete_certificate)
#
# 3. Recover a deleted certificate (begin_recover_deleted_certificate)
#
# 4. Purge a deleted certificate (purge_deleted_certificate)
# ----------------------------------------------------------------------------------------------------------


# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_url=VAULT_URL, credential=credential)

# Let's create certificates holding storage and bank accounts credentials. If the certificate
# already exists in the Key Vault, then a new version of the certificate is created.
print("\n.. Create Certificates")

bank_cert_name = "BankRecoverCertificate"
storage_cert_name = "ServerRecoverCertificate"

bank_certificate_poller = client.begin_create_certificate(
    certificate_name=bank_cert_name, policy=CertificatePolicy.get_default()
)
storage_certificate_poller = client.begin_create_certificate(
    certificate_name=storage_cert_name, policy=CertificatePolicy.get_default()
)
Beispiel #30
0
# Sample - demonstrates basic CRUD operations for the certificate contacts for a key vault.
#
# 1. Create contacts (create_contacts)
#
# 2. Get contacts (get_contacts)
#
# 3. Delete contacts (delete_contacts)
# ----------------------------------------------------------------------------------------------------------

# Instantiate a certificate client that will be used to call the service.
# Notice that the client is using default Azure credentials.
# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_ENDPOINT = os.environ["VAULT_ENDPOINT"]
credential = DefaultAzureCredential()
client = CertificateClient(vault_endpoint=VAULT_ENDPOINT,
                           credential=credential)
try:
    # First we create a list of Contacts that we would like to make the certificate contacts for this key vault.
    contact_list = [
        Contact(email="*****@*****.**", name="John Doe",
                phone="1111111111"),
        Contact(email="*****@*****.**",
                name="John Doe2",
                phone="2222222222"),
    ]

    # Creates and sets the certificate contacts for this key vault.
    client.create_contacts(contacts=contact_list)

    # Gets the certificate contacts for this key vault.
    contacts = client.get_contacts()