Skip to main content

..a decorative auth library for Tornado.

Project description

gadeu on PyPI gadeu on readthedocs

gadeu (가드) is a decorative auth library for Tornado.

This README is only a high-level introduction to gadeu. For more detailed documentation, please view the official docs at https://gadeu.readthedocs.io.

Installation

You can install gadeu from PyPI through usual means, such as pip:

   pip install gadeu

Usage

To use gadeu two things must be done; first you must register at least one authorization handler, and second you must apply one of the authorization decorators to a request handler method. Consider the following example:

    import tornado
    from gadeu import *
    from .api.FakeApi import FakeApi

    # you configure an authorization handler
    AuthorizationManager.setAuthorizationHandler(
        AuthorizationMethod.APIKEY,
        handlers.ApiKeyAuthorizationHandler(key=apiKeySecret)
    )

    # you create a tornado app
    app = tornado.web.Application()
    # you add some handlers for your app
    app.add_handlers('.*', [
        (r'/api/v2/fakes', FakeApi),
        (r'/api/v2/fakes/(?P<id>\d+)', FakeApi),
        (r'/api/v2/fakes/(?P<name>[\dA-Za-z]+)', FakeApi),
        (r'/api/v2/fakes/(?P<id>\d+)/(?P<name>[^/][\dA-Za-z]+)', FakeApi)
    ])

Elsewhere in your project, you defined FakeApi and decorated at least one handler:

    import tornado
    from gadeu import authorization

    class FakeApi(tornado.web.RequestHandler):    

        def initialize(self) -> None:
            pass

        @authorization.apiKey
        async def put(self, id:str, name:str) -> None:
            _d[id] = name
            self.set_status(204)

In the above example, FakeApi.put has been decorated with @authorization.apiKey which will force a check for a valid API Key. The expectations of that check are implemented via the ApiKeyAuthorizationHandler configured in the first few lines of the example. There are more options than are shown here, but this basic setup is enough for a server to check for a valid API Key.

If you need to generate an encryption key there is a TokenUtil class that exposes a createSecretKey(...) method which you can use for this purpose, example:

    from gadeu import *

    # never share this key! it should get stored to a keyvault and
    # managed securely as part of your app settings.
    secretKey = TokenUtil.createSecretKey(AuthorizationMethod.APIKEY)

You can also use TokenUtil to generate API Keys using your secret key.

    # share this token securely with your business partners, developers,
    # testers, etc that need to authorize requests with a server.
    apiKey = TokenUtil.createToken(secretKey, {'app':'bob123'}, AuthorizationMethod.APIKEY)

In the above example you can see a dictionary {'app':'bob123'}, this is a "claims object" that gets encoded into the resulting token (apiKey). See the section below Checking Claims for more information on how they can be accessed.

Currently, only apiKey and bearerToken security schemes are supported, with a plan to add others as they are requested, PR'd, or required for our own projects. Both apiKey and bearerToken tokens are encrypted, and unless you leak your secret keys the wider public should not be able to peek at the token contents (ie. the "claims" you've stored.) That said, it is NOT a good practice to store anything sensitive in a claim (such as keys, passwords, etc.)

Custom/Proprietary Authorization Methods

You can subclass AuthorizationHandler to implement custom behavior. You are encouraged to submit a PR if you find yourself implementing any well known security schemes such as:

  • mutualTLS
  • OAuth2
  • openIdConnect

Since we do not currently use these schemes there are not yet handlers for them, despite their popularity.

Checking Claims

In the future there will be decorators to facilitate claims assertions.

In the current implementation you can check claims "globally" from a custom validator function, or "locally" within your handler methods. Example:

    # you configure an authorization handler
    AuthorizationManager.setAuthorizationHandler(
        AuthorizationMethod.APIKEY,
        handlers.ApiKeyAuthorizationHandler(
            key=apiKeySecret,
            validator=lambda token,claims: claims.get('has_api_access', False) == True
        )
    )

    # elsewhere, you decorate your services, and check claims
    class FakeApi(tornado.web.RequestHandler):    

        @authorization.apiKey
        async def put(self, id:str, name:str) -> None:
            claims = self.request.arguments.get('claims', None)
            if claims.get('can_edit', False) != True:
                raise tornado.web.HTTPError(403)
            # do stuff

If claims is an argument name you already use (and therefore would be clobbered by gadeu) then you can configure a custom argument name in your AuthorizationHandler. Example:

    AuthorizationManager.setAuthorizationHandler(
        AuthorizationMethod.APIKEY,
        handlers.ApiKeyAuthorizationHandler(
            key=secretKey,
            claimsArgumentName='my_epic_arg_name')
    )

Lastly, TokenUtil can be used directly against a token to check claims. This may be useful for non-standard scenarios (token passing over a websocket connection for example), or if you are building user-tools for managing and verifying tokens. Example:

    secretKey = TokenUtil.createSecretKey(AuthorizationMethod.APIKEY)
    token = TokenUtil.createToken(
        secretKey, 
        { 'id':123, 'ts':datetime.now().isoformat() },
        AuthorizationMethod.APIKEY)
    claims = TokenUtil.getTokenClaims(
        secretKey,
        token,
        AuthorizationMethod.APIKEY)
    print(claims)

    # outputs:
    #
    # {'id': 123, 'ts': '2025-05-10T17:58:41.048820'}
    #

Contact

You can reach me on Discord or open an Issue on Github.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gadeu-0.0.8.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gadeu-0.0.8-py3-none-any.whl (12.8 kB view details)

Uploaded Python 3

File details

Details for the file gadeu-0.0.8.tar.gz.

File metadata

  • Download URL: gadeu-0.0.8.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3+

File hashes

Hashes for gadeu-0.0.8.tar.gz
Algorithm Hash digest
SHA256 cf774459d413d0588379ea33dcd088a73adb78fc5e4758b32b27fccd8effb726
MD5 15ff3b47d0b7fc589696fac2c80117f2
BLAKE2b-256 019d8a6b5229b80c65fdd16bbde3e437e8035a03907cb9f539ae22bd01492d76

See more details on using hashes here.

File details

Details for the file gadeu-0.0.8-py3-none-any.whl.

File metadata

  • Download URL: gadeu-0.0.8-py3-none-any.whl
  • Upload date:
  • Size: 12.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3+

File hashes

Hashes for gadeu-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 bca0501a793e6476e40d5dbe3242353460a146de27bfb3b2a9cb671dc39bc471
MD5 0a5bab4ee41f50a782f6d61386617a8a
BLAKE2b-256 a1ff0422d4f9bdcdcd57dffc55ef72b6b2c84decaf428edb04c457170e73faf4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page