A Python library to create and validate authentication tokens

Overview

handshake

A Python library to create and validate authentication tokens.

handshake is used to generate and validate arbitrary authentication tokens that contain arbitrary metadata and support expiration. It uses basic cryptographic primitives (hashing, HMACs) and is based around the concept of a shared private secret for security.

Example usage would be to create namespaced authentication tokens for clients of an API which another service can check is valid and hasn't expired. The tokens are safe to be made public, put in headers etc. and can be used like session tokens.

The tokens are strings in the format of:

arbitrary:data:here:timestamp:random:signature

All fields other than timestamp, random and signature are optional. Signatures are in the format of:

HMAC(arbitrary:data:here:timestamp:random){shared_secret}

The library is designed to allow whatever metadata is required into the token, such as the first parameter could be a namespace and the second parameter an object id. This allows tokens to be easily split between internal systems and uses while containing metadata or IDs for other objects.

For example, you could use handshake to allow an API to generate tokens which a client stores for a variable amount of time and can verify their state with other services. The arbitrary data prefix can be used to store an application namespace and the UUID of the object being referenced (such as user:uuid or service:recordtype:uuid). This library is of most use if you have multiple diverse systems, microservices or other distributed endpoints that require ad-hoc authentication and something like JWT or OAuth is overkill.

Installation

handshake is pure Python and has no dependancies. You can install handshake via pip:

$ pip install handshake

Any modern version of Python3 will be compatible.

Usage

handshake has one class providing two basic public functions. Examples:

import os
from handshake import AuthToken

# The shared secret, keep this private, can be str or bytes but needs to be
# from a cryptographically secure source
secret = os.urandom(128)

# Create the instance
token = AuthToken(secret)

# Basic token with no additional parameters
plain_token = token.create()
token.verify(plain_token)

# The token must be no more than 300 seconds old
plain_token = token.create()
token.verify(plain_token, time_range=300)

# Namespaced but no specific item, namespace is arbitrary
namespaced_token = token.create('namespace')
token.verify(namespaced_token)

# Namespaced and with an arbitrary item ID
from uuid import uuid4
client_token = token.create('user', uuid4())
token.verify(client_token)

# Lots of metadata
client_token = token.create('network', 'node', '12345', '67890')
token.verify(client_token)

# Use blake2s for hashes and signatures
from hashlib import blake2s
token = AuthToken(secret, hashfunc=blake2s)
blake2s_token = token.create()
token.verify(blake2s_token)

If a token fails to validate it raise the relevent exception:

# Create a token with one secret
token = AuthToken('a fixed secret string')
plain_token = token.create()

# Attempt to verify it with a different token, this is invalid
token_with_different_secret = AuthToken('not the same secret string')
token_with_different_secret.verify(plain_token)
# ... a child of handshake.errors.InvalidTokenError exception is raised

Limitations

The secret must be at least 16 bytes or characters and no more than 1024 bytes or characters. The total generated token length cannot be longer than 2048 characters.

Full API synopsis

handshake.AuthToken(secret=str_or_bool, hashfunc=function)

Initiates an AuthToken object using the specified secret. The secret is required. It must be either a string or a bytes and must be between 32 and 1024 characters or bytes in length. The secret should be sourced from a cryptographically safe random source, such as os.urandom.

hashfunc defaults to hashlib.sha256 but you can replace it with another hash function if you need to.

handshake.AuthToken.create(*arbitrary str)

Creates an authentication token.

handshake.AuthToken.verify(token=str, time_range=int)

Verifies an authentication token created with handshake.AuthToken.create().

time_range is an optional integer which if set specifies the valid time range the token must have been generated within. This is used to verify expiring tokens. It defaults to 0 which disables time range validation.

If the token is valid a tuple containing any arbitrary data in the token. For example a token of

arbitrary:data:here:timestamp:random:signature

If valid would return a tuple of:

('arbitrary', 'data', 'here')

If the token is invalid for any reason a handshake.errors.InvalidTokenError exception is raised (or a child exception of handshake.errors.InvalidTokenError). You can handle different errors by catching them specifically and the exception names describe the event:

import os
from handshake import AuthToken, errors

secret = os.urandom(128)
token = AuthToken(secret)
test_token = token.create()

try:
    token.verify(test_token)
except errors.TokenExpiredError as e:
    print(e)
except errors.TokenSignatureError as e:
    print(e)
except errors.InvalidTokenError as e:
    print(e)

Tests

There is a test suite that you can run by cloning this repository and executing:

$ make test

Contributing

All properly formatted and sensible pull requests, issues and comments are welcome.

You might also like...
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

Crie seus tokens de autenticação com o AScrypt.

AScrypt tokens O AScrypt é uma forma de gerar tokens de autenticação para sua aplicação de forma rápida e segura. Todos os tokens que foram, mesmo que

Local server that gives you your OAuth 2.0 tokens needed to interact with the Conta Azul's API

What's this? This is a django project meant to be run locally that gives you your OAuth 2.0 tokens needed to interact with Conta Azul's API Prerequisi

Creation & manipulation of PyPI tokens

PyPIToken: Manipulate PyPI API tokens PyPIToken is an open-source Python 3.6+ library for generating and manipulating PyPI tokens. PyPI tokens are ver

Two factor authentication system using azure services and python language and its api's
Two factor authentication system using azure services and python language and its api's

FUTURE READY TALENT VIRTUAL INTERSHIP PROJECT PROJECT NAME - TWO FACTOR AUTHENTICATION SYSTEM Resources used: * Azure functions(python)

Toolkit for Pyramid, a Pylons Project, to add Authentication and Authorization using Velruse (OAuth) and/or a local database, CSRF, ReCaptcha, Sessions, Flash messages and I18N

Apex Authentication, Form Library, I18N/L10N, Flash Message Template (not associated with Pyramid, a Pylons project) Uses alchemy Authentication Authe

This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Welcome to django-rest-auth Repository is unmaintained at the moment (on pause). More info can be found on this issue page: https://github.com/Tivix/d

Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes

Flask-HTTPAuth Simple extension that provides Basic and Digest HTTP authentication for Flask routes. Installation The easiest way to install this is t

Implements authentication and authorization as FastAPI dependencies

FastAPI Security Implements authentication and authorization as dependencies in FastAPI. Features Authentication via JWT-based OAuth 2 access tokens a

Releases(v0.2.1)
Object Moderation Layer

django-oml Welcome to the documentation for django-oml! OML means Object Moderation Layer, the idea is to have a mixin model that allows you to modera

Angel Velásquez 12 Aug 22, 2019
A simple username/password database authentication solution for Streamlit

TL;DR: This is a simple username/password login authentication solution using a backing database. Both SQLite and Airtable are supported.

Arvindra 49 Nov 25, 2022
Pingo provides a uniform API to program devices like the Raspberry Pi, BeagleBone Black, pcDuino etc.

Pingo provides a uniform API to program devices like the Raspberry Pi, BeagleBone Black, pcDuino etc. just like the Python DBAPI provides an uniform API for database programming in Python.

Garoa Hacker Clube 12 May 22, 2022
Plotly Dash plugin to allow authentication through 3rd party OAuth providers.

dash-auth-external Integrate your dashboards with 3rd parties and external OAuth providers. Overview Do you want to build a Plotly Dash app which pull

James Holcombe 15 Dec 11, 2022
A full Rest-API With Oauth2 and JWT for request & response a JSON file Using FastAPI and SQLAlchemy 🔑

Pexon-Rest-API A full Rest-API for request & response a JSON file, Building a Simple WorkFlow that help you to Request a JSON File Format and Handling

Yasser Tahiri 15 Jul 22, 2022
JSON Web Token implementation in Python

PyJWT A Python implementation of RFC 7519. Original implementation was written by @progrium. Sponsor If you want to quickly add secure token-based aut

José Padilla 4.5k Jan 09, 2023
Mock authentication API that acceccpts email and password and returns authentication result.

Mock authentication API that acceccpts email and password and returns authentication result.

Herman Shpryhau 1 Feb 11, 2022
OAuthlib support for Python-Requests!

Requests-OAuthlib This project provides first-class OAuth library support for Requests. The OAuth 1 workflow OAuth 1 can seem overly complicated and i

1.6k Dec 28, 2022
A Login/Registration GUI Application with SQLite database for manipulating data.

Login-Register_Tk A Login/Registration GUI Application with SQLite database for manipulating data. What is this program? This program is a GUI applica

Arsalan 1 Feb 01, 2022
JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction

JWT Key Confusion PoC (CVE-2015-9235) Written for the Hack the Box challenge - Under Construction This script performs a Java Web Token Key Confusion

Alex Fronteddu 1 Jan 13, 2022
Library - Recent and favorite documents

Thingy Thingy is used to quickly access recent and favorite documents. It's an XApp so it can work in any distribution and many desktop environments (

Linux Mint 23 Sep 11, 2022
User-related REST API based on the awesome Django REST Framework

Django REST Registration User registration REST API, based on Django REST Framework. Documentation Full documentation for the project is available at

Andrzej Pragacz 399 Jan 03, 2023
This program automatically logs you into a Zoom session at your alloted time

This program automatically logs you into a Zoom session at your alloted time. Optionally you can choose to have end the session at your allotted time.

9 Sep 19, 2022
Simplifying third-party authentication for web applications.

Velruse is a set of authentication routines that provide a unified way to have a website user authenticate to a variety of different identity provider

Ben Bangert 253 Nov 14, 2022
API-key based security utilities for FastAPI, focused on simplicity of use

FastAPI simple security API key based security package for FastAPI, focused on simplicity of use: Full functionality out of the box, no configuration

Tolki 154 Jan 03, 2023
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 2022
A flask extension for managing permissions and scopes

Flask-Pundit A simple flask extension to organize resource authorization and scoping. This extension is heavily inspired by the ruby Pundit library. I

Anurag Chaudhury 49 Dec 23, 2022
OpenConnect auth creditials collector.

OCSERV AUTH CREDS COLLECTOR V1.0 Зачем Изначально было написано чтобы мониторить какие данные вводятся в интерфейс ханипота в виде OpenConnect server.

0 Sep 23, 2022
Flask JWT Router is a Python library that adds authorised routes to a Flask app.

Read the docs: Flask-JWT-Router Flask JWT Router Flask JWT Router is a Python library that adds authorised routes to a Flask app. Both basic & Google'

Joe Gasewicz 52 Jan 03, 2023
row level security for FastAPI framework

Row Level Permissions for FastAPI While trying out the excellent FastApi framework there was one peace missing for me: an easy, declarative way to def

Holger Frey 315 Dec 25, 2022