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)
Authentication testing framework

What is this This is a framework designed to test authentication for web applications. While web proxies like ZAProxy and Burpsuite allow authenticate

DigeeX 140 Jul 06, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 29, 2022
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
Per object permissions for Django

django-guardian django-guardian is an implementation of per object permissions [1] on top of Django's authorization backend Documentation Online docum

3.3k Jan 01, 2023
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
Strong, Simple, and Precise security for Flask APIs (using jwt)

flask-praetorian Strong, Simple, and Precise security for Flask APIs API security should be strong, simple, and precise like a Roman Legionary. This p

Tucker Beck 321 Dec 18, 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
Official implementation of the AAAI 2022 paper "Learning Token-based Representation for Image Retrieval"

Token: Token-based Representation for Image Retrieval PyTorch training code for Token-based Representation for Image Retrieval. We propose a joint loc

Hui Wu 42 Dec 06, 2022
Python library for generating a Mastercard API compliant OAuth signature.

oauth1-signer-python Table of Contents Overview Compatibility References Usage Prerequisites Adding the Library to Your Project Importing the Code Loa

23 Aug 01, 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
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

95 Nov 28, 2022
Django Auth Protection This package logout users from the system by changing the password in Simple JWT REST API.

Django Auth Protection Django Auth Protection This package logout users from the system by changing the password in REST API. Why Django Auth Protecti

Iman Karimi 5 Oct 26, 2022
Ready to use and customizable Authentications and Authorisation management for FastAPI ⚡

AuthenticationX 💫 Ready-to-use and customizable Authentications and Oauth2 management for FastAPI ⚡ Source Code: https://github.com/yezz123/AuthX Doc

Yasser Tahiri 404 Dec 27, 2022
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
The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.

Authlib The ultimate Python library in building OAuth and OpenID Connect servers. JWS, JWK, JWA, JWT are included. Authlib is compatible with Python2.

Hsiaoming Yang 3.4k Jan 04, 2023
Python One-Time Password Library

PyOTP - The Python One-Time Password Library PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement tw

PyAuth 2.2k Dec 26, 2022
Djagno grpc authentication service with jwt auth

Django gRPC authentication service STEP 1: Install packages pip install -r requirements.txt STEP 2: Make migrations and migrate python manage.py makem

Saeed Hassani Borzadaran 3 May 16, 2022
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

Jacob Magnusson 111 Jan 07, 2023
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
Django server for Travel Mate (Project: nomad)

Travel Mate Server (Project: Nomad) Django 2.0 server for Travel Mate Contribute For new feature request in the app, open a new feature request on the

Travel Mate 41 May 29, 2022