Skip to main content

Flask-HmacAuth

Build Status A module to simplify HMAC-style authentication for RESTful APIs in Flask, which also builds in a simple RBAC concept and anti-replay via a timestamp. For GET requests, the path section and all parameters are hashed. For POST requests, the request body is added as well. By default, the module expects authentication via an X-Auth-Signature header and ACCOUNT_ID and TIMESTAMP parameters (holding the obvious values) to be present in the query string or request body. TIMESTAMP can be in any format datetime.fromtimestamp() can parse. ACCOUNT_ID will be used to lookup a given account’s secret and roles via an AccountBroker. If auth fails, the application throws a 403 back to the client. All of that can be changed, however.

The concept of an AccountBroker is used to separate this module from any actual user/role management logic. 2 trivial AccountBroker implementations have been provided.

Example

Server

from flask import Flask
from flask.ext.hmacauth import hmac_auth, DictAccountBroker, HmacManager

app = Flask(__name__)
accountmgr = DictAccountBroker(
    accounts={
        "admin": {"secret": ";hi^897t7utf", "rights": ["create", "edit", "delete", "view"]},
        "editor": {"secret": "afstr5afewr", "rights": ["create", "edit", "view"]},
        "guest": {"secret": "ASDFjoiu%i", "rights": ["view"]}
    })
hmacmgr = HmacManager(accountmgr, app)
...
@app.route('/api/v1/create')
@hmac_auth("create")
def create_thing():
    ...

Client

import requests
import time

path_and_query = "/api/v1/create?TIMESTAMP="+str(int(time.time()))+"&ACCOUNT_ID=admin&foo=bar"
host = "https://example.com"
sig=hmac.new(";hi^897t7utf", msg=path_and_query).hexdigest()
req = requests.get(host+path_and_query, headers={'X-Auth-Signature': sig})

AccountBroker

An AccountBroker is an object that intermediates between the HMAC authentication and your user/account store. It does this by exposing the following methods:

  • get_secret(account_id) - returns a string secret given an account ID. If the account does not exist, returns None

  • has_rights(account_id, rights) - returns True if account_id has all of the rights in the list rights, otherwise returns False. Returns False if the account does not exist.

  • is_active(account_id) - returns True if account_id is active (for whatever definition you want to define for active), otherwise returns False.

Flask-Hmacauth ships with 2 trivial AccountBroker implementations, a Dict-based AccountBroker (DictAccountBroker) and a static AccountBroker (StaticAccountBroker).

DictAccountBroker

Takes a dict of format:

{
    "accountID": {
        secret: "blahblah",
        rights: ["right1", "right2", "right3", ...]
    }
    ...
}

it also exposes the add_accounts and del_accounts methods to modify accounts on the fly.

StaticAccountBroker

Essentially disables all of the user and role management, and sets a static key for use in HMAC. NOTE, if you use this class you need to pass StaticAccountBroker.GET_ACCOUNT to HmacManager as the account_id parameter OR supply a dummy value for ACCOUNT_ID in the query string

Write your own

A very common case for larger applications will be user management via a database. In that case, your AuthenticationBroker class just needs to perform the requisite SQL queries to satisfy the the methods above and you’re good to go.

HmacManager

This is the meat of the module. This object contains the is_authorized method, which actually does the HMAC verification and role checks.

In the simple case, you just need to pass this object’s constructor the flask application object and an AccountBroker object. In more complex cases, where you want to change defaults, you have the following options:

  • app - this is the Flask application container

  • account_broker - this is the ApplicationBroker object

  • account_id - this is a callable, which when fed a request object will return the request’s account ID. The default value for this is lambda x: x.values.get(‘ACCOUNT_ID’)

  • signature - this is a callable, which when fed a request object will return the request’s signature. The default value for this is GET_SIGNATURE = lambda x: x.headers.get(‘X-Auth-Signature’).

  • timestamp - this is a callable, which when fed a request object will return the request’s timestamp. The default value for this is lambda x: x.values.get(‘TIMESTAMP’)

  • valid_time - number of seconds that a signed request is valid (based on the signed timestamp). defaults to 5

  • digest - digest type, defaults to hashlib.sha1

Download files

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

Source Distribution

flask-hmacauth-0.1.tar.gz (3.6 kB view details)

Uploaded Source

Built Distribution

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

flask_hmacauth-0.1-py2.7.egg (3.2 kB view details)

Uploaded Egg

File details

Details for the file flask-hmacauth-0.1.tar.gz.

File metadata

  • Download URL: flask-hmacauth-0.1.tar.gz
  • Upload date:
  • Size: 3.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for flask-hmacauth-0.1.tar.gz
Algorithm Hash digest
SHA256 90277dc7f62a516e9e43756e812054402c33e05d8278e4979ac91f1432d81ee9
MD5 cc08ea4ab33430c35e4a972fd330716e
BLAKE2b-256 a7ead8e9347bdc9ff0a36da93422e64758b2a8ba2b25135e0235d65993599243

See more details on using hashes here.

File details

Details for the file flask_hmacauth-0.1-py2.7.egg.

File metadata

File hashes

Hashes for flask_hmacauth-0.1-py2.7.egg
Algorithm Hash digest
SHA256 3ce5fad621ed3bab193cc571a96b4c077dee020ad97e196f5556d2a64ab116f6
MD5 0600d54dbe6d4a9ae7b366c7841e603c
BLAKE2b-256 37edc987ffc1d4e86518a9a02ae4c995e378ea465cca4d37c70060ab57a08b75

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 Sentry Error logging StatusPage Status page