Skip to main content

Anzar is a lightweight authentication and authorization framework that runs as a separate microservice

Project description

Anzar SDK Documentation

Server Middleware

The server SDK provides two middleware functions for protecting your routes using JWT tokens issued by your Anzar Auth container.

📝 Note: JWT vs. Session

Depending on what Authentication strategy you choose, use these middleware functions accordingly

Jwt

require_auth

Verifies the JWT token and attaches the authenticated user's ID to the request object. Use this to protect any route that requires a logged-in user.

import os

from flask import g
from flask import Flask, jsonify
from anzar.server.flask import require_auth, JwtAuth

app = Flask(__name__)

jwt_auth = JwtAuth(
    audience = os.getenv("AUDIENCE"),
    issuerBaseURL = os.getenv("ISSUER"),
)

@app.route("/protected")
@require_jwt(jwt_auth)
def me():
    return jsonify(g.user_id)

require_role

Verifies the JWT token and checks that the token includes a specific role. Use this to restrict routes to users with a particular permission level.

import os

from flask import g
from flask import Flask, jsonify
from anzar.server.flask import require_role, JwtAuth

app = Flask(__name__)

jwt_auth = JwtAuth(
    audience = os.getenv("AUDIENCE"),
    issuerBaseURL = os.getenv("ISSUER"),
)

@app.route("/admin")
@require_role(jwt_auth, roles="admin", permissions=["users:delete"])
def admin():
    return jsonify(f"admin panel, {g.user_id}")

Session

require_auth

Verifies the session and attaches the authenticated user's ID to the request object. Use this to protect routes when using session-based authentication instead of JWT tokens.

import os

from flask import g
from flask import Flask, jsonify
from anzar.server.flask import require_auth, SessionAuth

app = Flask(__name__)

session_auth = SessionAuth()

@app.route("/protected")
@require_session(session_auth)
def me():
    return jsonify(g.user_id)

require_role

Verifies the session and checks that the session includes a specific role. Use this to restrict routes to users with a particular permission level when using session-based authentication instead of JWT tokens.

import os

from flask import g
from flask import Flask, jsonify
from anzar.server import require_role, SessionAuth

app = Flask(__name__)

session_auth = SessionAuth()

@app.route("/admin")
@require_session_role(session_auth, roles="admin", permissions=["users:delete"])
def admin():
    return jsonify(f"admin panel, {g.user_id}")

Client

Install The Python SDK

In a python project run the following command to install the anzar package.

uv

$ uv add anzar

pip

# in a virtual env run
$ pip install anzar

Create Anzar Auth Instance

in your main entry file (main.py for example), import Anzar and create your auth instance

# Initialize once at application startup
# The SDK will communicate with your Anzar container at the configured api_url

from anzar import Anzar
from anzar.adapters import RedisStorage
from anzar.types import SdkOptions 

options = SdkOptions(storage=RedisStorage(), url="localhost:3000", auth="jwt")
anzar = Anzar(options)

if RedisStorage was chosen as an Adapter, make sure to install anzar as optional dependencie with redis extra === "uv" bash $ uv add anzar[redis] === "pip" bash $ pip install anzar[redis]


Basic Usage

Anzar provides authentication support for email and password.

📝 Note: Other methods of authentication will be implemented later

Sign Up

To sign up a user you need to call the method register with the user's information.

from anzar.types import AuthResponse, ErrorCode

(data, error) = await anzar.Auth.register({
  "username": "username",
  "email": "user@example.com",
  "password": "password"
})

if data:
    print(data)

if error:
    if error.code == ErrorCode.InvalidCredentials:
        show_error("Invalid email or password.")
    elif error.code == ErrorCode.AccountNotVerified:
        show_error("Please verify your email before logging in.")

📝 Note: By default, the users are automatically signed in after they successfully sign up. Disabling this behavior will be implemented later

Sign In

To sign in a user you need to call the method login.

from anzar.types import ApiException, AuthResponse, ErrorCode

(response, error) = await anzar.Auth.login(
    LoginRequest(email="user@example.com", password="password")
)
if error:
    print("code:", error.code)
    print("message:", error.message)
print(response)

Project details


Download files

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

Source Distribution

anzar-0.5.6.tar.gz (10.4 kB view details)

Uploaded Source

Built Distribution

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

anzar-0.5.6-py3-none-any.whl (17.2 kB view details)

Uploaded Python 3

File details

Details for the file anzar-0.5.6.tar.gz.

File metadata

  • Download URL: anzar-0.5.6.tar.gz
  • Upload date:
  • Size: 10.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.16 {"installer":{"name":"uv","version":"0.11.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for anzar-0.5.6.tar.gz
Algorithm Hash digest
SHA256 2e985a5655bb1241f200071e96784395e6aebfabe6fa14e1bd19ab87f2b270ba
MD5 79eb8d6117d41bf3ff7975adc5fb1336
BLAKE2b-256 6d8ac1e9f71450d5f2a9def05eca3508f9dc7944fb977396589343a217774f4b

See more details on using hashes here.

File details

Details for the file anzar-0.5.6-py3-none-any.whl.

File metadata

  • Download URL: anzar-0.5.6-py3-none-any.whl
  • Upload date:
  • Size: 17.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.16 {"installer":{"name":"uv","version":"0.11.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for anzar-0.5.6-py3-none-any.whl
Algorithm Hash digest
SHA256 04110c6e52862670c0094950017b1ac331846df4ba73e56a046b2d4e341b183f
MD5 bd62c91f21a028fee0db8fb91d72ced9
BLAKE2b-256 e7b4d5e1cd0bb057079bb1c9efd6ce489d968cc76ae3ccffecb0d84d78af90aa

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