sd-oauth2-client


Namesd-oauth2-client JSON
Version 1.4.2 PyPI version JSON
download
home_pagehttp://github.com/securedimensions/OAuth2Client
SummaryA client library for OAuth2
upload_time2024-05-24 08:38:10
maintainerNone
docs_urlNone
authorAndreas Matheus
requires_pythonNone
licenseNone
keywords
VCS
bugtrack_url
requirements requests
Travis-CI No Travis.
coveralls test coverage No coveralls.
            OAuth2Client
============
.. image:: https://img.shields.io/pypi/v/oauth2-client.svg
    :target: https://pypi.python.org/pypi/sd-oauth2-client

.. image:: https://img.shields.io/github/license/antechrestos/Oauth2Client.svg
    :target: https://raw.githubusercontent.com/antechrestos/OAuth2Client/master/LICENSE

Note
----

This library extends the original library `OAuth2Client` with the ability of `id_token`. To distinguish this library from the original `OAuth2Client` this library uses the prefix `sd`. Therefore, the PyPi project name is `sd-oauth2-client`.

Presentation
------------

OAuth2Client is a simple python client library for OAuth2. It is based on the requests_
    .. _requests: https://pypi.python.org/pypi/requests/


:warning: Starting version `1.2.0`, versions older that python `3.6.0` will not be supported anymore. This late version was released by the end 2016.

For those that are still using python 2.7, it won't be supported by the end of 2020 and all library shall stop supporting it.

Login process
-------------
For now it can handle two token process:

* Authorization code
* User Credentials
* Client Credentials

Authorization code
~~~~~~~~~~~~~~~~~~
Since authorization code process needs the user to accept the access to its data by the application, the library
starts locally a http server. You may put the host part of the ``redirect_uri`` parameter in your *hosts* file
pointing to your loop-back address. The server waits a ``GET`` requests with the  ``code`` as a query parameter.

Getting a couple of access token may be done like this:

.. code-block:: python

    scopes = ['scope_1', 'scope_2']

    service_information = ServiceInformation('https://authorization-server/oauth/authorize',
                                             'https://token-server/oauth/token',
                                             'client_id',
                                             'client_secret',
                                              scopes)
    manager = CredentialManager(service_information,
                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))
    redirect_uri = 'http://somewhere.io:8080/oauth/code'

    # Builds the authorization url and starts the local server according to the redirect_uri parameter
    url = manager.init_authorize_code_process(redirect_uri, 'state_test')
    _logger.info('Open this url in your browser\n%s', url)

    code = manager.wait_and_terminate_authorize_code_process()
    # From this point the http server is opened on 8080 port and wait to receive a single GET request
    # All you need to do is open the url and the process will go on
    # (as long you put the host part of your redirect uri in your host file)
    # when the server gets the request with the code (or error) in its query parameters
    _logger.debug('Code got = %s', code)
    manager.init_with_authorize_code(redirect_uri, code)
    _logger.debug('Access got = %s', manager._access_token)
    # Here access and refresh token may be used with self.refresh_token

Authorization code with Proof Key for Code Exchange (PKCE)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In case you can generate a couple of code verifier and code challenge as follows:

.. code-block:: python

    import base64
    import hashlib
    import logging
    import secrets
    from typing import Tuple

    def generate_sha256_pkce(length: int) -> Tuple[str, str]:
        if not (43 <= length <= 128):
            raise Exception("Invalid length: " % str(length))
        verifier = secrets.token_urlsafe(length)
        encoded = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode('ascii')).digest())
        challenge = encoded.decode('ascii')[:-1]
        return verifier, challenge


Then you can init authorization code workflow as follows

.. code-block:: python

    code_verifier, code_challenge = generate_sha256_pkce(64)
    url = manager.init_authorize_code_process(redirect_uri, 'state_test',
                                              code_challenge=code_challenge,
                                              code_challenge_method="S256")


or either generate the url

.. code-block:: python

    url = manager.generate_authorize_url(redirect_uri, 'state_test',
                                         code_challenge=code_challenge,
                                         code_challenge_method="S256")


And once you obtains the ``code`` exchange it as follows

.. code-block:: python

    manager.init_with_authorize_code(redirect_uri, code, code_verifier=code_verifier)


User credentials
~~~~~~~~~~~~~~~~
Getting a couple of access and refresh token is much easier:

.. code-block:: python

    scopes = ['scope_1', 'scope_2']

    service_information = ServiceInformation('https://authorization-server/oauth/authorize',
                                             'https://token-server/oauth/token',
                                             'client_id',
                                             'client_secret',
                                              scopes)
    manager = CredentialManager(service_information,
                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))
    manager.init_with_user_credentials('login', 'password')
    _logger.debug('Access got = %s', manager._access_token)
    # Here access and refresh token may be used

Client credentials
~~~~~~~~~~~~~~~~~~
You can also get a token with client credentials process

.. code-block:: python

    manager = CredentialManager(service_information,
                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))
    manager.init_with_client_credentials()
    # here application admin operation may be called

Refresh token
~~~~~~~~~~~~~
Provided that you kept a previous ``refresh_token``, you can initiate your credential manager with it:

.. code-block:: python

    manager = CredentialManager(service_information,
                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))
    manager.init_with_token('my saved refreshed token')

Token expiration
~~~~~~~~~~~~~~~~
``CredentialManager`` class handle token expiration by calling the ``CredentialManager._is_token_expired`` static method.
This implementation is not accurate for all OAuth server implementation. You'd better extend  ``CredentialManager`` class
and override ``_is_token_expired`` method.

Read other fields from token response
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``CredentialManager`` can be subclassed to handle other token response fields such as ``id_token`` in OpenId protocol.

.. code-block:: python

    class OpenIdCredentialManager(CredentialManager):
        def __init__(self, service_information, proxies=None):
            super(OpenIdCredentialManager, self).__init__(service_information, proxies)
            self.id_token = None

        def _process_token_response(self,  token_response, refresh_token_mandatory):
            id_token = token_response.get('id_token')
            OpenIdCredentialManager._check_id(id_token)
            super(OpenIdCredentialManager, self)._process_token_response(token_response, refresh_token_mandatory)
            self.id_token = id_token

        @staticmethod
        def _check_id(id_token):
            # check that open id token is valid
            pass



            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/securedimensions/OAuth2Client",
    "name": "sd-oauth2-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "Andreas Matheus",
    "author_email": "am@secure-dimensions.de",
    "download_url": "https://files.pythonhosted.org/packages/54/c6/6a91d0524c0ad309337d96ae3418d83c7a3a350cbf8625dd5c6858c534e1/sd_oauth2_client-1.4.2.tar.gz",
    "platform": null,
    "description": "OAuth2Client\n============\n.. image:: https://img.shields.io/pypi/v/oauth2-client.svg\n    :target: https://pypi.python.org/pypi/sd-oauth2-client\n\n.. image:: https://img.shields.io/github/license/antechrestos/Oauth2Client.svg\n    :target: https://raw.githubusercontent.com/antechrestos/OAuth2Client/master/LICENSE\n\nNote\n----\n\nThis library extends the original library `OAuth2Client` with the ability of `id_token`. To distinguish this library from the original `OAuth2Client` this library uses the prefix `sd`. Therefore, the PyPi project name is `sd-oauth2-client`.\n\nPresentation\n------------\n\nOAuth2Client is a simple python client library for OAuth2. It is based on the requests_\n    .. _requests: https://pypi.python.org/pypi/requests/\n\n\n:warning: Starting version `1.2.0`, versions older that python `3.6.0` will not be supported anymore. This late version was released by the end 2016.\n\nFor those that are still using python 2.7, it won't be supported by the end of 2020 and all library shall stop supporting it.\n\nLogin process\n-------------\nFor now it can handle two token process:\n\n* Authorization code\n* User Credentials\n* Client Credentials\n\nAuthorization code\n~~~~~~~~~~~~~~~~~~\nSince authorization code process needs the user to accept the access to its data by the application, the library\nstarts locally a http server. You may put the host part of the ``redirect_uri`` parameter in your *hosts* file\npointing to your loop-back address. The server waits a ``GET`` requests with the  ``code`` as a query parameter.\n\nGetting a couple of access token may be done like this:\n\n.. code-block:: python\n\n    scopes = ['scope_1', 'scope_2']\n\n    service_information = ServiceInformation('https://authorization-server/oauth/authorize',\n                                             'https://token-server/oauth/token',\n                                             'client_id',\n                                             'client_secret',\n                                              scopes)\n    manager = CredentialManager(service_information,\n                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))\n    redirect_uri = 'http://somewhere.io:8080/oauth/code'\n\n    # Builds the authorization url and starts the local server according to the redirect_uri parameter\n    url = manager.init_authorize_code_process(redirect_uri, 'state_test')\n    _logger.info('Open this url in your browser\\n%s', url)\n\n    code = manager.wait_and_terminate_authorize_code_process()\n    # From this point the http server is opened on 8080 port and wait to receive a single GET request\n    # All you need to do is open the url and the process will go on\n    # (as long you put the host part of your redirect uri in your host file)\n    # when the server gets the request with the code (or error) in its query parameters\n    _logger.debug('Code got = %s', code)\n    manager.init_with_authorize_code(redirect_uri, code)\n    _logger.debug('Access got = %s', manager._access_token)\n    # Here access and refresh token may be used with self.refresh_token\n\nAuthorization code with Proof Key for Code Exchange (PKCE)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nIn case you can generate a couple of code verifier and code challenge as follows:\n\n.. code-block:: python\n\n    import base64\n    import hashlib\n    import logging\n    import secrets\n    from typing import Tuple\n\n    def generate_sha256_pkce(length: int) -> Tuple[str, str]:\n        if not (43 <= length <= 128):\n            raise Exception(\"Invalid length: \" % str(length))\n        verifier = secrets.token_urlsafe(length)\n        encoded = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode('ascii')).digest())\n        challenge = encoded.decode('ascii')[:-1]\n        return verifier, challenge\n\n\nThen you can init authorization code workflow as follows\n\n.. code-block:: python\n\n    code_verifier, code_challenge = generate_sha256_pkce(64)\n    url = manager.init_authorize_code_process(redirect_uri, 'state_test',\n                                              code_challenge=code_challenge,\n                                              code_challenge_method=\"S256\")\n\n\nor either generate the url\n\n.. code-block:: python\n\n    url = manager.generate_authorize_url(redirect_uri, 'state_test',\n                                         code_challenge=code_challenge,\n                                         code_challenge_method=\"S256\")\n\n\nAnd once you obtains the ``code`` exchange it as follows\n\n.. code-block:: python\n\n    manager.init_with_authorize_code(redirect_uri, code, code_verifier=code_verifier)\n\n\nUser credentials\n~~~~~~~~~~~~~~~~\nGetting a couple of access and refresh token is much easier:\n\n.. code-block:: python\n\n    scopes = ['scope_1', 'scope_2']\n\n    service_information = ServiceInformation('https://authorization-server/oauth/authorize',\n                                             'https://token-server/oauth/token',\n                                             'client_id',\n                                             'client_secret',\n                                              scopes)\n    manager = CredentialManager(service_information,\n                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))\n    manager.init_with_user_credentials('login', 'password')\n    _logger.debug('Access got = %s', manager._access_token)\n    # Here access and refresh token may be used\n\nClient credentials\n~~~~~~~~~~~~~~~~~~\nYou can also get a token with client credentials process\n\n.. code-block:: python\n\n    manager = CredentialManager(service_information,\n                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))\n    manager.init_with_client_credentials()\n    # here application admin operation may be called\n\nRefresh token\n~~~~~~~~~~~~~\nProvided that you kept a previous ``refresh_token``, you can initiate your credential manager with it:\n\n.. code-block:: python\n\n    manager = CredentialManager(service_information,\n                                proxies=dict(http='http://localhost:3128', https='http://localhost:3128'))\n    manager.init_with_token('my saved refreshed token')\n\nToken expiration\n~~~~~~~~~~~~~~~~\n``CredentialManager`` class handle token expiration by calling the ``CredentialManager._is_token_expired`` static method.\nThis implementation is not accurate for all OAuth server implementation. You'd better extend  ``CredentialManager`` class\nand override ``_is_token_expired`` method.\n\nRead other fields from token response\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n``CredentialManager`` can be subclassed to handle other token response fields such as ``id_token`` in OpenId protocol.\n\n.. code-block:: python\n\n    class OpenIdCredentialManager(CredentialManager):\n        def __init__(self, service_information, proxies=None):\n            super(OpenIdCredentialManager, self).__init__(service_information, proxies)\n            self.id_token = None\n\n        def _process_token_response(self,  token_response, refresh_token_mandatory):\n            id_token = token_response.get('id_token')\n            OpenIdCredentialManager._check_id(id_token)\n            super(OpenIdCredentialManager, self)._process_token_response(token_response, refresh_token_mandatory)\n            self.id_token = id_token\n\n        @staticmethod\n        def _check_id(id_token):\n            # check that open id token is valid\n            pass\n\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A client library for OAuth2",
    "version": "1.4.2",
    "project_urls": {
        "Homepage": "http://github.com/securedimensions/OAuth2Client"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5b926004bb7454d84bbf8452f4e5afd8a63915b3f6352b28a2e6350b9ebd0669",
                "md5": "e385813e18f9d107c8f833607543d45d",
                "sha256": "6ae21f9bd0bacf2b11fb1903b04768ae2edddc9e8ed1a59412b30d3ac3aa410e"
            },
            "downloads": -1,
            "filename": "sd_oauth2_client-1.4.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e385813e18f9d107c8f833607543d45d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 12290,
            "upload_time": "2024-05-24T08:38:06",
            "upload_time_iso_8601": "2024-05-24T08:38:06.571614Z",
            "url": "https://files.pythonhosted.org/packages/5b/92/6004bb7454d84bbf8452f4e5afd8a63915b3f6352b28a2e6350b9ebd0669/sd_oauth2_client-1.4.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "54c66a91d0524c0ad309337d96ae3418d83c7a3a350cbf8625dd5c6858c534e1",
                "md5": "a5e0d45d64daa5de039c2e1b73b9de8e",
                "sha256": "78f530dd3a728855e992a926e4156a997616da8cfc6332f723e335b2109b57df"
            },
            "downloads": -1,
            "filename": "sd_oauth2_client-1.4.2.tar.gz",
            "has_sig": false,
            "md5_digest": "a5e0d45d64daa5de039c2e1b73b9de8e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 13922,
            "upload_time": "2024-05-24T08:38:10",
            "upload_time_iso_8601": "2024-05-24T08:38:10.231692Z",
            "url": "https://files.pythonhosted.org/packages/54/c6/6a91d0524c0ad309337d96ae3418d83c7a3a350cbf8625dd5c6858c534e1/sd_oauth2_client-1.4.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-24 08:38:10",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "securedimensions",
    "github_project": "OAuth2Client",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "requests",
            "specs": [
                [
                    ">=",
                    "2.5.0"
                ]
            ]
        }
    ],
    "lcname": "sd-oauth2-client"
}
        
Elapsed time: 0.41959s