Skip to content

Latest commit

 

History

History
76 lines (59 loc) · 3.36 KB

README.md

File metadata and controls

76 lines (59 loc) · 3.36 KB

NATS jwt lib for python

Python's library for generating JWT tokens for NATS server.

⚠️ Warning ⚠️

This library is not well-tested and is in the development stage.

The Author(s) is not a developer of the NATS, so may not understand zen of the NATS.

Notes

Scope level description
Code ℹ️ This library was inspired and based on official NATS's go library.
Code ℹ️ Author tried to save structure of code that GoLang version has, but it is not one-to-one due to languages specs.
Code ℹ️ In this library there is snippets.py that is targeting to make creation of accounts and users easier.
Tests ⚠️ Tests not covering all code.
Documentation ℹ️ NATS has powerful documentation for JWT. Recommended for reading.

Code Example

Code examples are using snippets.py which is not part of the go library.

Create Operator from seed

from nats_jwt.v2.snippets import Operator
from nats_jwt.v2.account_claims import Export
from nats_jwt.nkeys_ext import nkeys2
from nkeys import nkeys

# create raw seed - 32 'random' bytes
raw_seed: bytes = nkeys2.create_seed()

# create a new seed for operator. This seed now would look in base64 like:
# SO...
op_seed: bytes = nkeys2.encode_seed(nkeys.PREFIX_BYTE_OPERATOR, raw_seed)

# Tip: Also operator, account and user seeds can be created via prepared functions
# Note 1: those functions are returning nkeys.KeyPair objects (ed25519 generated keys)
# Note 2: You can extract seed from KeyPair object by calling seed() method
#
# nkeys2.create_operator_pair()
# nkeys2.create_account_pair()
# nkeys2.create_user_pair()

# now we can create an abstraction above this seed for operator operations
op = Operator(seed=op_seed)

# `create_account` will create new seed, KeyPair, AccountClaims with issuer set to operator's public key
# also, `Account` snippet object has signer key pair as object attribute (`_skp`) and when jwt generation
# is done jwt automatically is signed by this key pair (and `iat` is also set to current time).
ac = op.create_account("my_account")

ac.claims.name = "rewrite_name"
ac.claims.nats.exports.append(Export("my_export", "MY.CUSTOM.SUBJECT.>"))

# JWT for any snippet is generated by calling `jwt` property-method
jwt: str = ac.jwt

# now we can verify this jwt by calling `verify` operator method
if op.verify(jwt):
    print("account JWT is valid")
else:
    # should not happen :D
    print("account JWT is invalid")

us = ac.create_user("my_user")
if ac.verify(us.jwt):
    print("user JWT is valid")
else:
    # should not happen :D
    print("user JWT is invalid")

LICENSE

This library is licensed under the same LICENSE as the NATS's go library