Skip to content

Commit

Permalink
Merge pull request #54 from AzureAD/release-0.2.2
Browse files Browse the repository at this point in the history
Release 0.2.2
  • Loading branch information
abhidnya13 authored Apr 27, 2020
2 parents fae4931 + dff9a57 commit 3df9da0
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 10 deletions.
89 changes: 85 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,85 @@

# Contributing
# Microsoft Authentication Extensions for Python

The Microsoft Authentication Extensions for Python offers secure mechanisms for client applications to perform cross-platform token cache serialization and persistence. It gives additional support to the [Microsoft Authentication Library for Python (MSAL)](https://github.com/AzureAD/microsoft-authentication-library-for-python).

MSAL Python supports an in-memory cache by default and provides the [SerializableTokenCache](https://msal-python.readthedocs.io/en/latest/#msal.SerializableTokenCache) to perform cache serialization. You can read more about this in the MSAL Python [documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-python-token-cache-serialization). Developers are required to implement their own cache persistance across multiple platforms and Microsoft Authentication Extensions makes this simpler.

The supported platforms are Windows, Mac and Linux.
- Windows - [DPAPI](https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-use-data-protection) is used for encryption.
- MAC - The MAC KeyChain is used.
- Linux - [LibSecret](https://wiki.gnome.org/Projects/Libsecret) is used for encryption.

> Note: It is recommended to use this library for cache persistance support for Public client applications such as Desktop apps only. In web applications, this may lead to scale and performance issues. Web applications are recommended to persist the cache in session. Take a look at this [webapp sample](https://github.com/Azure-Samples/ms-identity-python-webapp).
## Installation

You can find Microsoft Authentication Extensions for Python on [Pypi](https://pypi.org/project/msal-extensions/).
1. If you haven't already, [install and/or upgrade the pip](https://pip.pypa.io/en/stable/installing/)
of your Python environment to a recent version. We tested with pip 18.1.
2. Run `pip install msal-extensions`.

## Versions

This library follows [Semantic Versioning](http://semver.org/).

You can find the changes for each version under
[Releases](https://github.com/AzureAD/microsoft-authentication-extensions-for-python/releases).

## Usage

The Microsoft Authentication Extensions library provides the `PersistedTokenCache` which accepts a platform-dependent persistence instance. This token cache can then be used to instantiate the `PublicClientApplication` in MSAL Python.

The token cache includes a file lock, and auto-reload behavior under the hood.



Here is an example of this pattern for multiple platforms (taken from the complete [sample here](https://github.com/AzureAD/microsoft-authentication-extensions-for-python/blob/dev/sample/token_cache_sample.py)):

```python
def build_persistence(location, fallback_to_plaintext=False):
"""Build a suitable persistence instance based your current OS"""
if sys.platform.startswith('win'):
return FilePersistenceWithDataProtection(location)
if sys.platform.startswith('darwin'):
return KeychainPersistence(location, "my_service_name", "my_account_name")
if sys.platform.startswith('linux'):
try:
return LibsecretPersistence(
location,
schema_name="my_schema_name",
attributes={"my_attr1": "foo", "my_attr2": "bar"},
)
except: # pylint: disable=bare-except
if not fallback_to_plaintext:
raise
logging.exception("Encryption unavailable. Opting in to plain text.")
return FilePersistence(location)

persistence = build_persistence("token_cache.bin")
print("Is this persistence encrypted?", persistence.is_encrypted)

cache = PersistedTokenCache(persistence)
```
Now you can use it in an MSAL application like this:
```python
app = msal.PublicClientApplication("my_client_id", token_cache=cache)
```

## Community Help and Support

We leverage Stack Overflow to work with the community on supporting Azure Active Directory and its SDKs, including this one!
We highly recommend you ask your questions on Stack Overflow (we're all on there!).
Also browse existing issues to see if someone has had your question before.

We recommend you use the "msal" tag so we can see it!
Here is the latest Q&A on Stack Overflow for MSAL:
[http://stackoverflow.com/questions/tagged/msal](http://stackoverflow.com/questions/tagged/msal)


## Contributing

All code is licensed under the MIT license and we triage actively on GitHub.

This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
Expand All @@ -9,6 +89,7 @@ When you submit a pull request, a CLA-bot will automatically determine whether y
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [[email protected]](mailto:[email protected]) with any additional questions or comments.

## We value and adhere to the Microsoft Open Source Code of Conduct

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
2 changes: 1 addition & 1 deletion msal_extensions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Provides auxiliary functionality to the `msal` package."""
__version__ = "0.2.1"
__version__ = "0.2.2"

import sys

Expand Down
5 changes: 4 additions & 1 deletion msal_extensions/cache_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys
import errno
import portalocker
from distutils.version import LooseVersion


class CrossPlatLock(object):
Expand All @@ -12,6 +13,8 @@ class CrossPlatLock(object):
"""
def __init__(self, lockfile_path):
self._lockpath = lockfile_path
# Support for passing through arguments to the open syscall was added in v1.4.0
open_kwargs = {'buffering': 0} if LooseVersion(portalocker.__version__) >= LooseVersion("1.4.0") else {}
self._lock = portalocker.Lock(
lockfile_path,
mode='wb+',
Expand All @@ -20,7 +23,7 @@ def __init__(self, lockfile_path):
# More information here:
# https://docs.python.org/3/library/fcntl.html#fcntl.lockf
flags=portalocker.LOCK_EX | portalocker.LOCK_NB,
buffering=0)
**open_kwargs)

def __enter__(self):
file_handle = self._lock.__enter__()
Expand Down
10 changes: 6 additions & 4 deletions msal_extensions/persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,14 @@ def __init__(self, location, entropy=''):
super(FilePersistenceWithDataProtection, self).__init__(location)

def save(self, content):
super(FilePersistenceWithDataProtection, self).save(
self._dp_agent.protect(content))
# type: (str) -> None
with open(self._location, 'wb+') as handle:
handle.write(self._dp_agent.protect(content))

def load(self):
return self._dp_agent.unprotect(
super(FilePersistenceWithDataProtection, self).load())
# type: () -> str
with open(self._location, 'rb') as handle:
return self._dp_agent.unprotect(handle.read())


class KeychainPersistence(BasePersistence):
Expand Down

0 comments on commit 3df9da0

Please sign in to comment.