Exemplo n.º 1
0
def test_serialization():
    expected = {
        "authority": "http://localhost",
        "clientId": "client-id",
        "homeAccountId": "object-id.tenant-id",
        "tenantId": "tenant-id",
        "username": "******",
        "version": "1.0",
    }

    record = AuthenticationRecord(
        expected["tenantId"],
        expected["clientId"],
        expected["authority"],
        expected["homeAccountId"],
        expected["username"],
    )
    serialized = record.serialize()

    assert json.loads(serialized) == expected

    deserialized = AuthenticationRecord.deserialize(serialized)

    assert sorted(vars(deserialized)) == sorted(vars(record))

    assert record.authority == deserialized.authority == expected["authority"]
    assert record.client_id == deserialized.client_id == expected["clientId"]
    assert record.home_account_id == deserialized.home_account_id == expected[
        "homeAccountId"]
    assert record.tenant_id == deserialized.tenant_id == expected["tenantId"]
    assert record.username == deserialized.username == expected["username"]
Exemplo n.º 2
0
 def _azure_interactive_auth(self):
     if self._authentication_record_json is None:
         _interactive_credential = DeviceCodeCredential(
             tenant_id=self._tenant_id,
             timeout=180,
             prompt_callback=None,
             _cache=load_persistent_cache(
                 TokenCachePersistenceOptions(
                     name=self._azure_cred_cache_name,
                     allow_unencrypted_storage=True,
                     cache_location=self._azure_cred_cache_location)))
         _auth_record = _interactive_credential.authenticate()
         self._authentication_record_json = _auth_record.serialize()
     else:
         deserialized_auth_record = AuthenticationRecord.deserialize(
             self._authentication_record_json)
         _interactive_credential = DeviceCodeCredential(
             tenant_id=self._tenant_id,
             timeout=180,
             prompt_callback=None,
             _cache=load_persistent_cache(
                 TokenCachePersistenceOptions(
                     name=self._azure_cred_cache_name,
                     allow_unencrypted_storage=True,
                     cache_location=self._azure_cred_cache_location)),
             authentication_record=deserialized_auth_record)
     return _interactive_credential
Exemplo n.º 3
0
def test_unknown_version(version):
    """deserialize should raise ValueError when the data doesn't contain a known version"""

    data = {
        "authority": "http://localhost",
        "clientId": "client-id",
        "homeAccountId": "object-id.tenant-id",
        "tenantId": "tenant-id",
        "username": "******",
    }

    if version:
        data["version"] = version

    with pytest.raises(ValueError, match=".*{}.*".format(version)) as ex:
        AuthenticationRecord.deserialize(json.dumps(data))
    assert str(SUPPORTED_VERSIONS) in str(ex.value)
Exemplo n.º 4
0
    def get_auth_record(self) -> AuthenticationRecord:
        result = None

        try:
            with open(AUTH_RECORD_LOCATION, 'r') as file:
                result = file.read()
            return AuthenticationRecord.deserialize(result)
        except IOError as ex:
            raise CLIException('Login to run this command') from ex
Exemplo n.º 5
0
def _get_cache_args(token_path: Path):
    cache_args = {
        'cache_persistence_options':
        TokenCachePersistenceOptions(name='parsedmarc')
    }
    auth_record = _load_token(token_path)
    if auth_record:
        cache_args['authentication_record'] = \
            AuthenticationRecord.deserialize(auth_record)
    return cache_args
Exemplo n.º 6
0
def test_serialization():
    """serialize should accept arbitrary additional key/value pairs, which deserialize should ignore"""

    attrs = ("authority", "client_id", "home_account_id", "tenant_id",
             "username")
    nums = (n for n in range(len(attrs)))
    record_values = {attr: next(nums) for attr in attrs}

    record = AuthenticationRecord(**record_values)
    serialized = record.serialize()

    # AuthenticationRecord's fields should have been serialized
    assert json.loads(serialized) == record_values

    deserialized = AuthenticationRecord.deserialize(serialized)

    # the deserialized record and the constructed record should have the same fields
    assert sorted(vars(deserialized)) == sorted(vars(record))

    # the constructed and deserialized records should have the same values
    assert all(
        getattr(deserialized, attr) == record_values[attr] for attr in attrs)
record = credential.authenticate()
print("\nAuthenticated first credential")

# The record contains no authentication secrets. You can serialize it to JSON for storage.
record_json = record.serialize()

# An authenticated credential is ready for use with a client. This request should succeed
# without prompting for authentication again.
client = SecretClient(VAULT_URL, credential)
secret_names = [s.name for s in client.list_properties_of_secrets()]
print("\nCompleted request with first credential")

# An authentication record stored by your application enables other credentials to access data from
# past authentications. If the cache contains sufficient data, this eliminates the need for your
# application to prompt for authentication every time it runs.
deserialized_record = AuthenticationRecord.deserialize(record_json)
new_credential = InteractiveBrowserCredential(
    cache_persistence_options=TokenCachePersistenceOptions(),
    authentication_record=deserialized_record)

# This request should also succeed without prompting for authentication.
client = SecretClient(VAULT_URL, new_credential)
secret_names = [s.name for s in client.list_properties_of_secrets()]
print("\nCompleted request with credential using shared cache")

# To isolate the token cache from other applications, you can provide a cache name to TokenCachePersistenceOptions.
separate_cache_credential = InteractiveBrowserCredential(
    cache_persistence_options=TokenCachePersistenceOptions(name="my_app"),
    authentication_record=deserialized_record)

# This request should prompt for authentication since the credential is using a separate cache.