Highly flexible library to manage and orchestrate JWT workflow

Overview

JWT Vault

Highly flexible library to manage and orchestrate JWT workflow

Build Status Build status codecov Version RepoSize Crates.io Crates.io Crates.io Contributors Gitter Say Thanks!

Examples | Website | Chat

TODO

  • Add more examples
  • Improve coverage

Features

  • Manages & Orchestrates JWT for user login, logout & renew
    • Option 1: DynamicVault (uses dynamic dispatch but requires considerable less boiler-plate code)
    • Option 2: DefaultVault (uses static dispatch but requires considerable more boiler-plate code)
  • Async ready
  • Easy start
  • No un-safe code
  • Runs on stable rust
  • Uses Argon (see video)
  • Library approach (Requires no runtime)
  • Supports plugable components
  • Invalidates old refresh upon new refresh token renewal
  • Invalidates old authentication upon new authentication token renewal
  • Cross feeding not allowed
  • Handles Thundering herd problem upon authentication token expiry
  • Works with any web-server, any password hashing, and any backend (here)
  • Fully functional webserver with actix and postgres

Quickstart

Prerequisite:

 [dependencies]
 jwtvault = "*"
$ curl https://raw.githubusercontent.com/sgrust01/jwtvault/master/generate_certificates.sh > ./generate_certificates.sh
$ chmod 700 generate_certificates.sh && ./generate_certificates.sh

Option 1: DynamicVault

use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;

use jwtvault::prelude::*;

fn main() {
    let hasher = ArgonPasswordHasher::default();
    // User: John Doe
    let user_john = "john_doe";
    let password_for_john = "john";
    // Save value 'hashed_password_for_john' to persistent storage
    // This is more relevant during user signup/password reset
    let hashed_password_for_john = hasher.hash_user_password(user_john, password_for_john).unwrap();

    // User: Jane Doe
    let user_jane = "jane_doe";
    let password_for_jane = "jane";
    // Save 'hashed_password_for_jane' to persistent storage
    // This is more relevant during user signup/password reset
    let hashed_password_for_jane = hasher.hash_user_password(user_jane, password_for_jane).unwrap();

    let mut users = HashMap::new();

    // load users and their password from database/somewhere
    users.insert(user_john.to_string(), hashed_password_for_john.to_string());
    users.insert(user_jane.to_string(), hashed_password_for_jane.to_string());

    // Setup app users
    let login = LoginInfo::new(users);

     // Initialize vault
    let mut vault = DynamicVault::default(Box::new(login));

    // John needs to login now
    let token = block_on(vault.login(
        user_john,
        password_for_john,
        None,
        None,
    ));
    let token = token.ok().unwrap();
    // When John presents authentication token, it can be used to restore John's session info
    let server_refresh_token = block_on(resolve_session_from_client_authentication_token(
        &mut vault,
        user_john,
        token.authentication(),
    ));
    let server_refresh_token = server_refresh_token.ok().unwrap();

    // server_refresh_token (variable) contains server method which captures client private info
    // which never leaves the server
    let private_info_about_john = server_refresh_token.server().unwrap();
    let key = digest::<_, DefaultHasher>(user_john);
    let data_on_server_side = private_info_about_john.get(&key).unwrap();

    // server_refresh_token (variable) contains client method which captures client public info
    // which is also send back to client
    assert!(server_refresh_token.client().is_none());

    // Check out the data on client and server which are public and private respectively
    println!("[Private] John Info: {}",
             String::from_utf8_lossy(data_on_server_side.as_slice()).to_string());

    // lets renew authentication token
    let new_token = block_on(vault.renew(
        user_john,
        token.refresh(),
        None,
    ));
    let new_token = new_token.ok().unwrap();

    // When John presents new authentication token it can be used to restore session info
    let result = block_on(resolve_session_from_client_authentication_token(
        &mut vault,
        user_john,
        new_token.as_str(),
    ));
    let _ = result.ok().unwrap();
}

Option 2: DefaultVault

use jwtvault::prelude::*;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;


fn main() {

    let mut users = HashMap::new();

    let loader = CertificateManger::default();

    // User: John Doe
    let user_john = "john_doe";
    let password_for_john = "john";

    // This should ideally be pre-computed during user sign-up/password reset/change password
    let hashed_password_for_john = hash_password_with_argon(
        password_for_john,
        loader.password_hashing_secret().as_str(),
    ).unwrap();

    // User: Jane Doe
    let user_jane = "jane_doe";
    let password_for_jane = "jane";

    // This should ideally be pre-computed during user sign-up/password reset/change password
    let hashed_password_for_jane = hash_password_with_argon(
        password_for_jane,
        loader.password_hashing_secret().as_str(),
    ).unwrap();

    // load users and their (argon hashed) password from database/somewhere
    users.insert(user_john.to_string(), hashed_password_for_john);
    users.insert(user_jane.to_string(), hashed_password_for_jane);

    // Initialize vault
    let mut vault = DefaultVault::new(loader, users, false);

    // John needs to login now
    let token = block_on(vault.login(
        user_john,
        password_for_john,
        None,
        None,
    ));
    let token = token.ok().unwrap();
    // When John presents authentication token, it can be used to restore John's session info
    let server_refresh_token = block_on(resolve_session_from_client_authentication_token(
        &mut vault,
        user_john,
        token.authentication(),
    ));
    let server_refresh_token = server_refresh_token.ok().unwrap();

    // server_refresh_token (variable) contains server method which captures client private info
    // which never leaves the server
    let private_info_about_john = server_refresh_token.server().unwrap();
    let key = digest::<_, DefaultHasher>(user_john);
    let data_on_server_side = private_info_about_john.get(&key).unwrap();

    // server_refresh_token (variable) contains client method which captures client public info
    // which is also send back to client
    assert!(server_refresh_token.client().is_none());

    // Check out the data on client and server which are public and private respectively
    println!("[Private] John Info: {}",
             String::from_utf8_lossy(data_on_server_side.as_slice()).to_string());

    // lets renew authentication token
    let new_token = block_on(vault.renew(
        user_john,
        token.refresh(),
        None,
    ));
    let new_token = new_token.ok().unwrap();

    // When John presents new authentication token it can be used to restore session info
    let result = block_on(resolve_session_from_client_authentication_token(
        &mut vault,
        user_john,
        new_token.as_str(),
    ));
    let _ = result.ok().unwrap();
}

Workflows

  • To begin use login with user and password

    • Upon successful login is provides user will be provided with JWT pair (authentication/refresh)

    • Authentication token is then provided to access any resources

    • Refresh token is used to renew an authentication token upon expiry

  • Use resolve_session_from_client_authentication_token with user and authentication_token to restore user session

  • Use renew with user and refresh_token to generate new authentication token

  • Use logout with user and authentication_token will remove all tokens associated with the user

  • Use helper continue_generate_temporary_token to generate temporary token for user

    • Temporary token creates temporary session, and does not corrupt the original session info
    • Temporary token cannot be used to login/logout/renew/revoke original session
    • Temporary token does not have refresh key (this is intentional), to avoid token refresh
    • Note: DynamicVault users can directly use instance method generate_temporary_token
    • Typical use-case: Forgot Password
  • Use helper resolve_temporary_session_from_client_authentication_token to restore user temporary session

    • Temporary session are isolated instance, and thus has no fingerprints of the originals session
    • Typical use-case: Reset Password
You might also like...
OpenSK is an open-source implementation for security keys written in Rust that supports both FIDO U2F and FIDO2 standards.
OpenSK is an open-source implementation for security keys written in Rust that supports both FIDO U2F and FIDO2 standards.

OpenSK This repository contains a Rust implementation of a FIDO2 authenticator. We developed this as a Tock OS application and it has been successfull

Fast, simple and REST compliant file-server with public/private key authentication written in Rust

stormi Stormi is a fast and simple file-server with public/private key authentication How does it work? Stormi accepts multipart/form-data form with m

Decode, explore, and sign JWTs
Decode, explore, and sign JWTs

JWT Explorer A utility for inspecting, modifying, and attacking JWTs. Supports Windows and Linux and probably also works on macOS but this has not bee

Tools for manipulating JSON Web Tokens, JWS, JWE, and JWK in Rust
Tools for manipulating JSON Web Tokens, JWS, JWE, and JWK in Rust

Rusty JWT Tools A collection of JWT utilities. This repository is part of the source code of Wire. You can find more information at wire.com or by con

A set of Rust libraries to interact with apple's private APIs and servers.

apple-private-apis A set of Rust libraries to interact with apple's private APIs and servers, made for use in SideInstaller. Library Description omnis

Simple crate to login to Pinterest and get the cookies via Chromiumoxide to simulate a browser

Simple crate to login to Pinterest and get the cookies via Chromiumoxide to simulate a browser (open a real browser actually), to use the Pinterest API without needing a developer account or an API key or anything that costs money :).

A highly extensible runner that can execute any workflow.

Astro run Astro Run is a highly extensible runner that can execute any workflow. Features Workflow runtime for Docker Support for gRPC server to coord

AI-TOML Workflow Specification (aiTWS), a comprehensive and flexible specification for defining arbitrary Ai centric workflows.

AI-TOML Workflow Specification (aiTWS) The AI-TOML Workflow Specification (aiTWS) is a flexible and extensible specification for defining arbitrary wo

Keyscope is a key and secret workflow (validation, invalidation, etc.) tool built in Rust
Keyscope is a key and secret workflow (validation, invalidation, etc.) tool built in Rust

✅ Automate your key and secret validation workflows 🤠 Over 30 different providers 🤖 Export to JSON, audit via CSV 🔑 Keyscope Keyscope is a key and

Command-line tool that provides a workflow for extending, editing, diffing, and writing to vim-style grep lines.

Grug Grug is a command-line tool that provides a workflow for expanding, editing, diffing, and writing edits to files using vim-styled grep lines (suc

Twidge is a fresh approach to productivity. It integrates with your workflow and allows you to be your most productive self.

Twidge A productivity app which is an extension to your mind Twidge is a cross platform productivity app, powered by rust, tauri, prisma-client-rust T

📦✨ your favorite rust -> wasm workflow tool!
📦✨ your favorite rust - wasm workflow tool!

📦 ✨ wasm-pack Your favorite Rust → Wasm workflow tool! Docs | Contributing | Chat Built with 🦀 🕸 by The Rust and WebAssembly Working Group About Th

📝 A template for creating WASM + Typescript + Rust workflow libraries.
📝 A template for creating WASM + Typescript + Rust workflow libraries.

Create Rust + TypeScript libraries with ease! PR'S WELCOMED! ✨ Inspiration I wanted to create a WebAssembly/Rust library with additional JS features,

Afterglow-Server provides back-end APIs for the Afterglow workflow engine.

Afterglow-Server 🚧 Note: This project is still heavily in development and is at an early stage. Afterglow-Server provides back-end APIs for the After

Beaker helps simplify CosmWasm development workflow.
Beaker helps simplify CosmWasm development workflow.

Beaker Beaker makes it easy to scaffold a new cosmwasm app, with all of the dependencies for osmosis hooked up, interactive console, and a sample fron

Git Explorer: cross-platform git workflow improvement tool inspired by Magit
Git Explorer: cross-platform git workflow improvement tool inspired by Magit

Gex Git workflow improvement CLI tool inspired by Magit. This project is still under initial development, but I am actively dogfooding it and features

A workflow tool for quickly running / testing something you are working on

runfast What is it? This is a program intended to be run in a project directory to set up a project run command, and remember it so we dont have to ty

Simple backend app with Actix-web, JWT and MongoDB

Actix Web JWT Example Simple backend app with Actix-web, JWT and MongoDB (JWT Token, Protect Route, Login & Register) While developing the web service

A Rust Boilerplate server with GraphQL API, Diesel, PostgreSQL, session authentication and JWT
A Rust Boilerplate server with GraphQL API, Diesel, PostgreSQL, session authentication and JWT

Canduma rust Graphql A Rust authentication server with GraphQL API, Diesel, PostgreSQL session authentication and JWT This repository contains a Graph

Comments
  • Enable build.rs to work on macOS

    Enable build.rs to work on macOS

    I changed the cfg! option in build.rs to allow for the library to build on macOS as well as Linux. I used the unix target_family instead of zeroing in on linux because I think it's safe to assume that a unix operating system would have sh to run the script to generate certs.

    opened by ELD 2
Owner
Saurav Gupta
Saurav Gupta
JWT lib in rust

jsonwebtoken API documentation on docs.rs See JSON Web Tokens for more information on what JSON Web Tokens are. Installation Add the following to Carg

Vincent Prouillet 1.1k Jan 3, 2023
vault client using jwt authentication that define environment variables from vault secrets before executing into something else

envlt envlt, like env, allows you to define environment variables and then execute into something else, but instead of static values, it uses using si

Eric Burghard 6 Nov 13, 2022
A minimal jwt implementation for OIDC

Compact JWT Json Web Tokens (JWT) are a popular method for creating signed transparent tokens that can be verified by clients and servers. They are en

Kanidm 4 Dec 29, 2021
WebCipher - JWT encryption/decryption algorithms + a JWK Store implementation

webcipher provides JWT authentication utilities and storage mechanism for caching keys and optimizing decryption/encryption processes.

Wavy 1 May 1, 2022
SD-JWT Rust Reference Implementation

SD-JWT Rust Reference Implementation This is the reference implementation of the IETF SD-JWT specification written in Rust. Supported version: 6. Note

OpenWallet Foundation Labs 4 Dec 19, 2023
Rust library for HTTP authentication. Parses challenge lists, responds to Basic and Digest challenges. Likely to be extended with server support and additional auth schemes.

Rust library for HTTP authentication. Parses challenge lists, responds to Basic and Digest challenges. Likely to be extended with server support and a

Scott Lamb 3 Jun 10, 2022
A OAuth2 server library, for use in combination with actix or other frontends, featuring a set of configurable and pluggable backends.

oxide-auth A OAuth2 server library, for use in combination with common web servers, featuring a set of configurable and pluggable backends. About oxid

null 471 Dec 29, 2022
Extensible, strongly-typed Rust OAuth2 client library

OAuth2 An extensible, strongly-typed implementation of OAuth2 (RFC 6749). Documentation is available on docs.rs. Release notes are available on GitHub

David Ramos 602 Dec 25, 2022
An auth system/library for Rust applications

Rust : Forbidden (WIP) An experimental auth library for Rust applications. Goals This crate is to define a common set of traits and idioms to provide

Mario Montoya 9 Nov 8, 2022
An oauth2 client implementation providing the Device, Installed and Service Account flows.

yup-oauth2 is a utility library which implements several OAuth 2.0 flows. It's mainly used by google-apis-rs, to authenticate against Google services.

Lewin Bormann 174 Dec 30, 2022