### Install Authlib with Django Source: https://docs.authlib.org/en/stable/basic/install.html Install Authlib along with the Django framework. ```bash $ pip install Authlib Django ``` -------------------------------- ### Install Authlib with Starlette Source: https://docs.authlib.org/en/stable/basic/install.html Install Authlib along with the httpx and Starlette libraries. ```bash $ pip install Authlib httpx Starlette ``` -------------------------------- ### Install Authlib with Httpx Source: https://docs.authlib.org/en/stable/basic/install.html Install Authlib along with the httpx library for HTTP requests. ```bash $ pip install Authlib httpx ``` -------------------------------- ### Install Authlib from Source Source: https://docs.authlib.org/en/stable/basic/install.html After obtaining the source code, navigate to the directory and install Authlib using pip. ```bash $ cd authlib $ pip install . ``` -------------------------------- ### Install Authlib with Flask Source: https://docs.authlib.org/en/stable/basic/install.html Install Authlib along with the Flask framework. ```bash $ pip install Authlib Flask ``` -------------------------------- ### Install Authlib with Requests Source: https://docs.authlib.org/en/stable/basic/install.html Install Authlib along with the requests library for HTTP requests. ```bash $ pip install Authlib requests ``` -------------------------------- ### Install Authlib with Pip Source: https://docs.authlib.org/en/stable/basic/install.html Use this command to install the Authlib package and its dependencies. ```bash $ pip install Authlib ``` -------------------------------- ### Query Client Example Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Example implementation for querying a client by its ID, typically used with SQLAlchemy. ```python def query_client(client_id): return Client.query.filter_by(client_id=client_id).first() ``` -------------------------------- ### Example OAuth Cache Implementation Source: https://docs.authlib.org/en/stable/oauth1/client/web/flask.html An example implementation of a cache instance required by the OAuth registry. It must provide delete, get, and set methods. ```python from flask import Flask class OAuthCache: def __init__(self, app: Flask) -> None: self.app = app def delete(self, key: str) -> None: pass def get(self, key: str) -> str | None: pass def set(self, key: str, value: str, expires: int | None = None) -> None: pass ``` -------------------------------- ### Query Token Example Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Example implementation for querying a token by client ID and token string, often used with SQLAlchemy. ```python def query_token(client_id, oauth_token): return Token.query.filter_by( client_id=client_id, oauth_token=oauth_token ).first() ``` -------------------------------- ### Example Authorization Callback URL Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html An example of the server redirecting the user-agent back to the client's callback URI with an OAuth token and verifier. ```http http://printer.example.com/ready? oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884 ``` -------------------------------- ### Initialize AuthorizationServer with Query Client Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html Instantiate the AuthorizationServer with a function to query client details. This is a standard way to set up the server when the application starts. ```python from authlib.integrations.flask_oauth1 import AuthorizationServer def query_client(client_id): return Client.query.filter_by(client_id=client_id).first() server = AuthorizationServer(app, query_client=query_client) ``` -------------------------------- ### Example Token Request POST Request Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html An example of a client requesting token credentials using its temporary credentials over TLS. ```http POST /token HTTP/1.1 Host: photos.example.net Authorization: OAuth realm="Photos", oauth_consumer_key="dpf43f3p2l4k3l03", oauth_token="hh5s93j4hdidpola", oauth_signature_method="HMAC-SHA1", oauth_timestamp="137131201", oauth_nonce="walatlh", oauth_verifier="hfdp7dh39dks9884", oauth_signature="gKgrFCywp7rO0OXSjdot%2FIHF7IU%3D" ``` -------------------------------- ### Example Authorization Request URL Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html An example of a client redirecting a user-agent to the server's Resource Owner Authorization endpoint. ```http https://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola ``` -------------------------------- ### Example Temporary Credentials Request Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html This is an example of a POST request to the temporary credentials endpoint. It includes the Authorization header with OAuth parameters. ```http POST /initiate HTTP/1.1 Host: photos.example.net Authorization: OAuth realm="Photos", oauth_consumer_key="dpf43f3p2l4k3l03", oauth_signature_method="HMAC-SHA1", oauth_timestamp="137131200", oauth_nonce="wIjqoS", oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready", oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D" ``` -------------------------------- ### Example Token Response Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html An example of a server response containing token credentials after validating a token request. ```http HTTP/1.1 200 OK Content-Type: application/x-www-form-urlencoded oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00 ``` -------------------------------- ### Example Token Request Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html This is an example of a POST request to the token endpoint. It is used by the client to request token credentials after the user has authorized the application. ```http POST /token HTTP/1.1 Host: photos.example.net Authorization: OAuth realm="Photos", ``` -------------------------------- ### Example Authorization Callback URL Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html After user approval, the server redirects the user-agent to this callback URI. It includes the oauth_token and oauth_verifier. ```http http://printer.example.com/ready?oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884 ``` -------------------------------- ### Example Authorization Request URL Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html This is an example URL for an authorization request. The client redirects the user-agent to this endpoint to obtain user approval. ```http https://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola ``` -------------------------------- ### Example Temporary Credentials Response Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html This is an example HTTP response from the temporary credentials endpoint. It contains the oauth_token, oauth_token_secret, and oauth_callback_confirmed status. ```http HTTP/1.1 200 OK Content-Type: application/x-www-form-urlencoded oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03& oauth_callback_confirmed=true ``` -------------------------------- ### JWS Compact Serialization Example Source: https://docs.authlib.org/en/stable/jose/jws.html Illustrates the structure of a JWS compact serialization, which is a URL-safe string representation of signed or MACed content. This example is for display purposes only. ```text eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9 . eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt cGxlLmNvbS9pc19yb290Ijp0cnVlfQ . dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk ``` -------------------------------- ### Making Requests with a Token Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Demonstrates how to manually pass a token object to request methods like GET, POST, PUT, and DELETE. This is useful when automatic token fetching is not configured. ```python token = OAuth1Token.find(name='twitter', user=request.user) oauth.twitter.get(url, token=token) oauth.twitter.post(url, token=token) oauth.twitter.put(url, token=token) oauth.twitter.delete(url, token=token) ``` -------------------------------- ### SQLAlchemy Query Client Function Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/resource-server.html Example of a `query_client` function using SQLAlchemy to fetch a client by its ID. Assumes a `Client` model exists. ```python def query_client(client_id): # assuming ``Client`` is the model return Client.query.filter_by(client_id=client_id).first() ``` -------------------------------- ### General JWS JSON Serialization Example Source: https://docs.authlib.org/en/stable/jose/jws.html Demonstrates the General JWS JSON Serialization Syntax, which allows for multiple signatures. Line breaks within values are for display purposes only. ```json { "payload": "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ", "signatures":[ {"protected":"eyJhbGciOiJSUzI1NiJ9", "header":{"kid":"2010-12-29"}, "signature": "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZ mh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjb KBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHl b1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZES c6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AX LIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"}, {"protected":"eyJhbGciOiJFUzI1NiJ9", "header":{"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"}, "signature": "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8IS lSApmWQxfKTUJqPP3-Kg6NU1Q"}] } ``` -------------------------------- ### JWT Encode Example Source: https://docs.authlib.org/en/stable/jose/jwt.html Demonstrates the JWT encoding process using a header, payload, and private key. The `jwt.encode` method creates the signed JWT string. ```python >>> from authlib.jose import jwt >>> header = {'alg': 'RS256'} >>> payload = {'iss': 'Authlib', 'sub': '123', ...} >>> private_key = read_file('private.pem') >>> s = jwt.encode(header, payload, private_key) ``` -------------------------------- ### JWK Structure Example Source: https://docs.authlib.org/en/stable/jose/jwk.html An example of an Elliptic Curve Public Key represented as a JSON Web Key (JWK). ```json { "kty": "EC", "crv": "P-256", "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", "kid": "iss-a" } ``` -------------------------------- ### JWT Decode Example Source: https://docs.authlib.org/en/stable/jose/jwt.html Shows how to decode a JWT string into its payload claims using a public key. Be aware of security implications mentioned in the documentation regarding default decoding behavior. ```python >>> from authlib.jose import jwt >>> public_key = read_file('public.pem') >>> claims = jwt.decode(s, public_key) ``` -------------------------------- ### Clone Authlib Repository Source: https://docs.authlib.org/en/stable/basic/install.html Clone the public Authlib repository from GitHub to get the source code. ```bash $ git clone git://github.com/authlib/authlib.git ``` -------------------------------- ### Configure Supported Signature Methods Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/customize.html Set the OAUTH1_SUPPORTED_SIGNATURE_METHODS configuration to enable specific signature methods. This example enables HMAC-SHA1, PLAINTEXT, and RSA-SHA1. ```python OAUTH1_SUPPORTED_SIGNATURE_METHODS = ['HMAC-SHA1', 'PLAINTEXT', 'RSA-SHA1'] ``` -------------------------------- ### Encode JWT with Authlib Source: https://docs.authlib.org/en/stable/jose/index.html A simple example demonstrating how to encode a JWT using Authlib's `jwt` module. Ensure you have a private key file (e.g., 'private.pem') for signing. ```python from authlib.jose import jwt with open('private.pem', 'rb') as f: key = f.read() payload = {'iss': 'Authlib', 'sub': '123', ...} header = {'alg': 'RS256'} s = jwt.encode(header, payload, key) ``` -------------------------------- ### Async OAuth 1.0 Operations with HTTPX Source: https://docs.authlib.org/en/stable/oauth1/client/http/httpx.html Demonstrates fetching request and access tokens, and making authenticated GET, POST, PUT, and DELETE requests using AsyncOAuth1Client. Requires `await` for all operations. ```python # fetching request token request_token = await client.fetch_request_token(request_token_url) # fetching access token access_token = await client.fetch_access_token(access_token_url) # normal requests await client.get(...) await client.post(...) await client.put(...) await client.delete(...) ``` -------------------------------- ### Enable Authlib Debug Logging Source: https://docs.authlib.org/en/stable/basic/logging.html Configure Python's logging module to capture and display debug messages from Authlib. This setup directs logs to standard output. ```python import logging import sys log = logging.getLogger('authlib') log.addHandler(logging.StreamHandler(sys.stdout)) log.setLevel(logging.DEBUG) ``` -------------------------------- ### SQLAlchemy Query Token Function Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/resource-server.html Example of a `query_token` function using SQLAlchemy to fetch a token credential by client ID and token. Assumes a `TokenCredential` model exists. ```python def query_token(client_id, oauth_token): return TokenCredential.query.filter_by(client_id=client_id, oauth_token=oauth_token).first() ``` -------------------------------- ### Flattened JWS JSON Serialization Example Source: https://docs.authlib.org/en/stable/jose/jws.html Shows the Flattened JWS JSON Serialization Syntax, which is a simpler structure for JWS with a single signature. Line breaks within values are for display purposes only. ```json { "payload": "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ", "protected":"eyJhbGciOiJFUzI1NiJ9", "header": {"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"}, "signature": "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8IS lSApmWQxfKTUJqPP3-Kg6NU1Q" } ``` -------------------------------- ### Server Initialization Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Initialize the AuthorizationServer with a Flask app and client query function. ```APIDOC ## Server Initialization ### Description Initialize the AuthorizationServer with a Flask app and client query function. ### Parameters * **app** – A Flask app instance * **query_client** – A function to get client by client_id. The client model class MUST implement the methods described by `ClientMixin`. * **token_generator** – A function to generate token ``` -------------------------------- ### Initialize FastAPI App with Session Middleware Source: https://docs.authlib.org/en/stable/oauth1/client/web/fastapi.html Set up a FastAPI application and add SessionMiddleware for storing temporary credentials during OAuth flows. Ensure a strong secret key is used in production. ```python from fastapi import FastAPI from starlette.middleware.sessions import SessionMiddleware app = FastAPI() # we need this to save temporary credential in session app.add_middleware(SessionMiddleware, secret_key="some-random-string") ``` -------------------------------- ### Initialize Resource Protector Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Initializes a ResourceProtector with necessary query and nonce validation functions. ```python require_oauth = ResourceProtector( app, query_client=query_client, query_token=query_token, exists_nonce=exists_nonce, ) ``` -------------------------------- ### Initialize AuthorizationServer in Flask Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Initialize the AuthorizationServer with a Flask app instance and a client query function. Ensure the app and query_client are properly configured. ```python server = AuthorizationServer(app=app, query_client=query_client) ``` -------------------------------- ### ResourceProtector Initialization Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Initialize a ResourceProtector with necessary query and nonce checking functions. ```APIDOC ## ResourceProtector(app=None, query_client=None, query_token=None, exists_nonce=None) ### Description A protecting method for resource servers. Initialize a resource protector with these methods: 1. query_client 2. query_token, 3. exists_nonce ### Parameters - **app** (Flask app instance, optional) - The Flask application instance. - **query_client** (callable, optional) - A function to query the client by ID. - **query_token** (callable, optional) - A function to query the token by client ID and token. - **exists_nonce** (callable, optional) - A function to check if a nonce already exists. ``` -------------------------------- ### Implement Client Model with ClientMixin Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html Client models must implement `authlib.oauth1.ClientMixin` and provide methods for retrieving client secrets and redirect URIs. ```python from authlib.oauth1 import ClientMixin class Client(ClientMixin, db.Model): id = db.Column(db.Integer, primary_key=True) client_id = db.Column(db.String(48), index=True) client_secret = db.Column(db.String(120), nullable=False) default_redirect_uri = db.Column(db.Text, nullable=False, default='') user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE') ) user = db.relationship('User') def get_default_redirect_uri(self): return self.default_redirect_uri def get_client_secret(self): return self.client_secret def get_rsa_public_key(self): return None ``` -------------------------------- ### JWS JSON Serialization Header Object Example - Authlib Source: https://docs.authlib.org/en/stable/jose/specs/rfc7515.html An example of a header object for JWS JSON Serialization. This structure can be a single dict for flattened serialization or a list of dicts for standard serialization. ```json { "protected: {"alg": "HS256"}, "header": {"kid": "jose"} } ``` -------------------------------- ### Get Temporary Credential Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html Retrieves temporary credential data from the cache and constructs a TemporaryCredential object. ```python def get_temporary_credential(self, request): key = "a-key-prefix:{}".format(request.token) data = cache.get(key) # TemporaryCredential shares methods from TemporaryCredentialMixin return TemporaryCredential(data) ``` -------------------------------- ### Delete Temporary Credential from Cache Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Example of deleting a temporary credential from a cache using a generated key based on the request token. ```python def delete_temporary_credential(self, request): key = "a-key-prefix:{}".format(request.token) ``` -------------------------------- ### Authorize Access Token and Fetch Profile Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Handle the callback from the third-party provider, fetch the access token, and retrieve user profile information. This is typically done in a separate route that the provider redirects back to. ```python def authorize(request): twitter = oauth.create_client('twitter') token = twitter.authorize_access_token(request) resp = twitter.get('account/verify_credentials.json') resp.raise_for_status() profile = resp.json() # do something with the token and profile return '...' ``` -------------------------------- ### Initialize AuthorizationServer with Custom Token Generator Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html Initialize the AuthorizationServer, passing a custom token generator function. This allows for specific control over how tokens are created. ```python server = AuthorizationServer( app, query_client=query_client, token_generator=token_generator ) ``` -------------------------------- ### Enable Session Middleware for Starlette Source: https://docs.authlib.org/en/stable/oauth1/client/web/starlette.html Add SessionMiddleware to your Starlette application to enable session support for OAuth 1.0 request tokens. Ensure 'itsdangerous' is installed. ```python from starlette.applications import Starlette from starlette.middleware.sessions import SessionMiddleware app = Starlette() app.add_middleware(SessionMiddleware, secret_key="some-random-string") ``` -------------------------------- ### Initialize OAuth 1.0 Client Source: https://docs.authlib.org/en/stable/oauth1/client/http/index.html Initialize an OAuth 1.0 client using either the Requests or HTTPX integration. This requires your client ID and client secret. ```APIDOC ## Initialize OAuth 1.0 Client This section demonstrates how to initialize an OAuth 1.0 client. You can use either the Requests-based client or the asynchronous HTTPX-based client. ### Code Example ```python # using requests client from authlib.integrations.requests_client import OAuth1Session client_id = 'Your Twitter client key' client_secret = 'Your Twitter client secret' client = OAuth1Session(client_id, client_secret) # using httpx client from authlib.integrations.httpx_client import AsyncOAuth1Client client = AsyncOAuth1Client(client_id, client_secret) ``` ``` -------------------------------- ### Register Custom HMAC-SHA256 Signature Method Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/customize.html Extend signature methods by defining a custom verification function and registering it with AuthorizationServer and ResourceProtector. This example implements HMAC-SHA256. ```python import hmac from authlib.common.encoding import to_bytes from authlib.oauth1.rfc5849 import signature def verify_hmac_sha256(request): text = signature.generate_signature_base_string(request) key = escape(request.client_secret or '') key += '&' key += escape(request.token_secret or '') sig = hmac.new(to_bytes(key), to_bytes(text), hashlib.sha256) return binascii.b2a_base64(sig.digest())[:-1] AuthorizationServer.register_signature_method( 'HMAC-SHA256', verify_hmac_sha256 ) ResourceProtector.register_signature_method( 'HMAC-SHA256', verify_hmac_sha256 ) ``` -------------------------------- ### Initialize CacheAuthorizationServer in Django Source: https://docs.authlib.org/en/stable/oauth1/provider/django/authorization-server.html Instantiate the CacheAuthorizationServer with your Client and Token models. Ensure these models are imported from your project's models. ```python from your_project.models import Client, Token from authlib.integrations.django_oauth1 import CacheAuthorizationServer authorization_server = CacheAuthorizationServer(Client, Token) ``` -------------------------------- ### Enable Custom HMAC-SHA256 Signature Method Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/customize.html After registering a custom signature method, update OAUTH1_SUPPORTED_SIGNATURE_METHODS to include the new method. This example configures the server to use only HMAC-SHA256. ```python OAUTH1_SUPPORTED_SIGNATURE_METHODS = ['HMAC-SHA256'] ``` -------------------------------- ### Initialize OAuth Instance for Starlette Source: https://docs.authlib.org/en/stable/oauth1/client/web/starlette.html Instantiate the OAuth object for Starlette integrations. This is the first step before registering clients. ```python from authlib.integrations.starlette_client import OAuth oauth = OAuth() ``` -------------------------------- ### Implement create_token_credential Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html Re-implementation of the `create_token_credential` method to create and save a token credential. It uses details from the temporary credential. ```python def create_token_credential(self, request): oauth_token = generate_token(36) oauth_token_secret = generate_token(48) temporary_credential = request.credential token_credential = TokenCredential( oauth_token=oauth_token, oauth_token_secret=oauth_token_secret, client_id=temporary_credential.get_client_id(), user_id=temporary_credential.get_user_id(), ) # if the credential has a save method token_credential.save() return token_credential ``` -------------------------------- ### Create OAuth1Auth Instance Source: https://docs.authlib.org/en/stable/oauth1/client/http/index.html Create an OAuth1Auth instance with your client credentials and access token details. This object can be used to authenticate requests. ```python # if using requests from authlib.integrations.requests_client import OAuth1Auth # if using httpx from authlib.integrations.httpx_client import OAuth1Auth auth = OAuth1Auth( client_id='..', client_secret='..', token='oauth_token value', token_secret='oauth_token_secret value', ... ) ``` -------------------------------- ### Resource Owner Authorization Endpoint Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html This endpoint manages the GET and POST requests for resource owner authorization. It checks the authorization request, renders an authorization template, and creates the authorization response. ```python @app.route('/authorize', methods=['GET', 'POST']) def authorize(): # make sure that user is logged in for yourself if request.method == 'GET': try: req = server.check_authorization_request() return render_template('authorize.html', req=req) except OAuth1Error as error: return render_template('error.html', error=error) granted = request.form.get('granted') if granted: grant_user = current_user else: grant_user = None try: return server.create_authorization_response(grant_user=grant_user) except OAuth1Error as error: return render_template('error.html', error=error) ``` -------------------------------- ### Initiate Temporary Credential Endpoint Source: https://docs.authlib.org/en/stable/oauth1/provider/django/authorization-server.html Create a POST endpoint for clients to fetch temporary credentials. This view requires the HTTP POST method. ```python from django.views.decorators.http import require_http_methods @require_http_methods(["POST"]) def initiate_temporary_credential(request): return server.create_temporary_credential_response(request) ``` -------------------------------- ### OAuth 1.0 HTTP Client with Requests Source: https://docs.authlib.org/en/stable/oauth1/client/index.html Use this client for scripts, CLIs, or service-to-service communication where your Python code directly fetches tokens and calls APIs. Ensure you have the `requests` library installed. ```python from authlib.integrations.requests_client import OAuth1Session client = OAuth1Session(client_id, client_secret) request_token = client.fetch_request_token(request_token_url) # ... redirect user, then: token = client.fetch_access_token(access_token_url) resp = client.get('https://api.example.com/data') ``` -------------------------------- ### Create Token Credential Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Re-implementation of creating and saving a token credential into the database. Ensure the credential has a save method. ```python def create_token_credential(self, request): oauth_token = generate_token(36) oauth_token_secret = generate_token(48) temporary_credential = request.credential token_credential = TokenCredential( oauth_token=oauth_token, oauth_token_secret=oauth_token_secret, client_id=temporary_credential.get_client_id(), user_id=temporary_credential.get_user_id(), ) # if the credential has a save method token_credential.save() return token_credential ``` -------------------------------- ### Implement TemporaryCredential Model with TemporaryCredentialMixin Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html Temporary credential models should implement `authlib.oauth1.TemporaryCredentialMixin` to manage request tokens and secrets. ```python from authlib.oauth1 import TemporaryCredentialMixin class TemporaryCredential(TemporaryCredentialMixin, db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE') ) user = db.relationship('User') client_id = db.Column(db.String(48), index=True) oauth_token = db.Column(db.String(84), unique=True, index=True) oauth_token_secret = db.Column(db.String(84)) oauth_verifier = db.Column(db.String(84)) oauth_callback = db.Column(db.Text, default='') def get_client_id(self): return self.client_id def get_redirect_uri(self): return self.oauth_callback def check_verifier(self, verifier): return self.oauth_verifier == verifier def get_oauth_token(self): return self.oauth_token def get_oauth_token_secret(self): return self.oauth_token_secret ``` -------------------------------- ### Resource Owner Authorization Endpoint Source: https://docs.authlib.org/en/stable/oauth1/provider/django/authorization-server.html Implement the endpoint for resource owner authorization. This view handles both GET requests to display the authorization page and POST requests to process the user's decision. ```python from django.shortcuts import render def authorize(request): # make sure that user is logged in for yourself if request.method == 'GET': try: req = server.check_authorization_request(request) context = {'req': req} return render(request, 'authorize.html', context) except OAuth1Error as error: context = {'error': error} return render(request, 'error.html', context) granted = request.POST.get('granted') if granted: grant_user = request.user else: grant_user = None try: return server.create_authorization_response(request, grant_user) except OAuth1Error as error: context = {'error': error} return render(request, 'error.html', context) ``` -------------------------------- ### Register Remote App with Configuration Loading Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Register a remote application, assuming client ID and secret are loaded from framework configuration. This simplifies registration when credentials are managed externally. ```python oauth.register( name='twitter', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', api_base_url='https://api.twitter.com/1.1/', ) ``` -------------------------------- ### Initialize OAuth Registry with Cache Source: https://docs.authlib.org/en/stable/oauth1/client/web/flask.html Initialize the OAuth registry with a cache instance to store temporary credentials. This is recommended for security over using Flask sessions. ```python oauth = OAuth(app, cache=cache) # or initialize lazily oauth = OAuth() oauth.init_app(app, cache=cache) ``` -------------------------------- ### Compute JWK Thumbprint Source: https://docs.authlib.org/en/stable/jose/specs/rfc7638.html Demonstrates how to import a raw key and compute its thumbprint using the `.thumbprint()` method. ```APIDOC ## Compute JWK Thumbprint ### Description This example shows how to import a raw key and compute its thumbprint using the `.thumbprint()` method available on the `Key` object. ### Method ```python from authlib.jose import JsonWebKey raw = read_file('rsa.pem') key = JsonWebKey.import_key(raw) thumbprint_value = key.thumbprint() ``` ### Usage This method is available on all Key classes (`OctKey`, `RSAKey`, `ECKey`, `OKPKey`). The thumbprint can be used as an identifier for the JWK, especially if the key lacks a `kid`. ``` -------------------------------- ### Initialize OAuth 1.0 Client Source: https://docs.authlib.org/en/stable/oauth1/client/http/index.html Initialize an OAuth 1.0 client using either the Requests or HTTPX integration. Replace 'Your Twitter client key' and 'Your Twitter client secret' with your actual API credentials. ```python client_id = 'Your Twitter client key' client_secret = 'Your Twitter client secret' # using requests client from authlib.integrations.requests_client import OAuth1Session client = OAuth1Session(client_id, client_secret) # using httpx client from authlib.integrations.httpx_client import AsyncOAuth1Client client = AsyncOAuth1Client(client_id, client_secret) ``` -------------------------------- ### Initiate Temporary Credentials Endpoint Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html This route handles POST requests to initiate the OAuth1 temporary credential process. It relies on the server's `create_temporary_credentials_response` method. ```python @app.route('/initiate', methods=['POST']) def initiate_temporary_credential(): return server.create_temporary_credentials_response() ``` -------------------------------- ### Shared Token Fetcher Initialization Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Initialize the OAuth registry with a shared `fetch_token` function that can handle tokens for multiple services. This simplifies token management across different providers. ```python def fetch_token(name, request): token = OAuth1Token.find( name=name, user=request.user ) return token.to_token() # initialize OAuth registry with this fetch_token function oauth = OAuth(fetch_token=fetch_token) ``` -------------------------------- ### Initialize OAuth Registry Later Source: https://docs.authlib.org/en/stable/oauth1/client/web/flask.html Initialize the OAuth registry later using the init_app() method. This is useful if you need to configure the app before initializing Authlib. ```python oauth = OAuth() oauth.init_app(app) ``` -------------------------------- ### Registering OAuth 2.0 Grant and Endpoint Source: https://docs.authlib.org/en/stable/basic/intro.html Demonstrates how to register a grant type and an endpoint for an OAuth 2.0 server. This is useful when customizing or extending server functionality. ```python authorization_server.register_grant(AuthorizationCodeGrant) authorization_server.register_endpoint(RevocationEndpoint) ``` -------------------------------- ### Import OKP Key for JWK Source: https://docs.authlib.org/en/stable/jose/specs/rfc8037.html Load and import an OKP key for use with JSON Web Key (JWK). The 'kty' value must be 'OKP'. ```python from authlib.jose import JsonWebKey with open('ed25519-pkcs8.pem', 'rb') as f: key = f.read() # MUST use "OKP" as "kty" value JsonWebKey.import_key(key, {'kty': 'OKP'}) ``` -------------------------------- ### Fetching Resources with Automatic Token Retrieval Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Once a `fetch_token` function is registered, you can make API requests by simply passing the `request` object. Authlib will automatically find and use the appropriate token. ```python def get_twitter_tweets(request): resp = oauth.twitter.get('statuses/user_timeline.json', request=request) resp.raise_for_status() return resp.json() ``` -------------------------------- ### Dynamic Key Loading by KID Source: https://docs.authlib.org/en/stable/jose/jws.html Demonstrates dynamic key loading for JWS deserialization based on the 'kid' (Key ID) parameter in the JWS header. This is useful when multiple keys are in use. ```python def load_key(header, payload): kid = header['kid'] return get_key_by_kid(kid) jws.deserialize_compact(s, load_key) ``` -------------------------------- ### Implement create_authorization_verifier Source: https://docs.authlib.org/en/stable/oauth1/provider/django/api.html Re-implementation of the `create_authorization_verifier` method to generate and bind an oauth_verifier to a temporary credential. Ensure the verifier is returned. ```python def create_authorization_verifier(self, request): verifier = generate_token(36) temporary_credential = request.credential user_id = request.user.id temporary_credential.user_id = user_id temporary_credential.oauth_verifier = verifier # if the credential has a save method temporary_credential.save() # remember to return the verifier return verifier ``` -------------------------------- ### Download Authlib Zipball Source: https://docs.authlib.org/en/stable/basic/install.html Download the main zipball of the Authlib source code from GitHub. ```bash $ curl -OL https://github.com/authlib/authlib/zipball/main ``` -------------------------------- ### Import OAuth for Web Frameworks Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Import the OAuth class specific to your web framework (Flask, Django, or Starlette). Initialize the OAuth registry. ```python # for Flask framework from authlib.integrations.flask_client import OAuth # for Django framework from authlib.integrations.django_client import OAuth # for Starlette framework from authlib.integrations.starlette_client import OAuth oauth = OAuth() ``` -------------------------------- ### Download Authlib Tarball Source: https://docs.authlib.org/en/stable/basic/install.html Download the main tarball of the Authlib source code from GitHub. ```bash $ curl -OL https://github.com/authlib/authlib/tarball/main ``` -------------------------------- ### Fetch Access Token Source: https://docs.authlib.org/en/stable/oauth1/client/http/index.html After user authorization, fetch the access token using the callback response. This involves parsing the authorization response and then requesting the access token from the server. ```python resp_url = 'https://example.com/twitter?oauth_token=gA..H&oauth_verifier=fcg..1Dq' client.parse_authorization_response(resp_url) access_token_url = 'https://api.twitter.com/oauth/access_token' token = client.fetch_access_token(access_token_url) print(token) save_access_token(token) ``` -------------------------------- ### Implement TokenCredential Model with TokenCredentialMixin Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html Token credential models must implement `authlib.oauth1.TokenCredentialMixin` for accessing protected resources. ```python from authlib.oauth1 import TokenCredentialMixin class TokenCredential(TokenCredentialMixin, db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE') ) user = db.relationship('User') client_id = db.Column(db.String(48), index=True) oauth_token = db.Column(db.String(84), unique=True, index=True) oauth_token_secret = db.Column(db.String(84)) def get_oauth_token(self): return self.oauth_token def get_oauth_token_secret(self): return self.oauth_token_secret ``` -------------------------------- ### Initialize OAuth Registry with Flask App Source: https://docs.authlib.org/en/stable/oauth1/client/web/flask.html Initialize the OAuth registry with your Flask application instance. This is the standard way to set up Authlib for Flask. ```python from authlib.integrations.flask_client import OAuth oauth = OAuth(app) ``` -------------------------------- ### AuthorizationServer Class Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/api.html Flask implementation of authlib.rfc5849.AuthorizationServer. Initialize it with Flask app instance, client model class and cache. ```APIDOC class authlib.integrations.flask_oauth1.AuthorizationServer(_app =None_, _query_client =None_, _token_generator =None_) Initialize it with Flask app instance, client model class and cache: ``` server = AuthorizationServer(app=app, query_client=query_client) ``` ``` -------------------------------- ### Configure JWS with Private Headers Source: https://docs.authlib.org/en/stable/jose/jws.html Instantiate `JsonWebSignature` with a list of allowed private header parameter names to enable validation for custom headers. ```python private_headers = ['h1', 'h2'] jws = JsonWebSignature(private_headers=private_headers) ``` -------------------------------- ### Enable Insecure Transport for Local Development Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/index.html When developing an OAuth 1.0 provider on your localhost, set this environment variable to true to allow insecure transport. This is a development-only setting. ```bash export AUTHLIB_INSECURE_TRANSPORT=true ``` -------------------------------- ### Registering a Token Fetcher Function Source: https://docs.authlib.org/en/stable/oauth1/client/web/index.html Configure Authlib to automatically fetch the user's token by registering a `fetch_token` function with `oauth.register`. This function should retrieve the token from your storage. ```python def fetch_twitter_token(request): token = OAuth1Token.find( name='twitter', user=request.user ) return token.to_token() # we can registry this ``fetch_token`` with oauth.register oauth.register( 'twitter', # ... fetch_token=fetch_twitter_token, ) ``` -------------------------------- ### Handle OAuth Login and Callback in FastAPI Source: https://docs.authlib.org/en/stable/oauth1/client/web/fastapi.html Implement endpoints for initiating the OAuth login process and handling the callback with the user's token. This requires access to the Starlette Request object. ```python from starlette.requests import Request @app.get("/login/twitter") async def login_via_twitter(request: Request): redirect_uri = request.url_for('auth_via_twitter') return await oauth.twitter.authorize_redirect(request, redirect_uri) @app.get("/auth/twitter") async def auth_via_twitter(request: Request): token = await oauth.twitter.authorize_access_token(request) # do something with the token return dict(token) ``` -------------------------------- ### Initialize AuthorizationServer Lazily with init_app Source: https://docs.authlib.org/en/stable/oauth1/provider/flask/authorization-server.html Initialize the AuthorizationServer lazily using init_app after the Flask application is created. This is useful for deferred initialization. ```python server = AuthorizationServer() server.init_app(app, query_client=query_client) ```