### Django Project Setup
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Basic steps to start a new Django project and run the development server. Ensure the port matches your redirect URI.
```bash
django-admin startproject mysite
python manage.py migrate
python manage.py runserver localhost:5000
```
--------------------------------
### Install Identity for Quart
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Installs the Identity library with Quart support using pip. This is a prerequisite for using the library with Quart applications.
```shell
pip install identity[quart]
```
--------------------------------
### Django Index View Example
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
A simple Django view that returns a 'Hello, world' HTTP response. This serves as a basic starting point for a Django application.
```python
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. Everyone can read this line.")
```
--------------------------------
### Install Identity Django Package
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Installs the Identity library with Django support using pip. This command adds the necessary dependencies to your project.
```bash
pip install identity[django]
```
--------------------------------
### Install Quart-session with Redis Support
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Installs the `Quart-session` package with Redis backing store support. This is required for managing user sessions in the Quart application.
```shell
pip install quart-session[redis]
```
--------------------------------
### Install Identity Package with Framework Support
Source: https://github.com/rayluo/identity/blob/dev/README.md
Install the identity library for Python, specifying support for different web frameworks like Django, Flask, or Quart. Ensure quotes are used for compatibility across terminals.
```bash
pip install "identity[django]"
```
```bash
pip install "identity[flask]"
```
```bash
pip install "identity[quart]"
```
--------------------------------
### Install Identity Flask Dependency
Source: https://github.com/rayluo/identity/blob/dev/docs/flask.rst
Installs the identity library with Flask support using pip. This command adds the necessary packages to your Python environment.
```bash
pip install identity[flask]
```
--------------------------------
### Python Web App Login Initialization Example
Source: https://github.com/rayluo/identity/blob/dev/docs/generic.rst
Example of initializing the identity.web.Auth object in a Python web application. This sets up the necessary components for handling user authentication.
```python
import identity.web
# Assuming 'session' is an existing session object with dict-like interface
# session = ...
auth = identity.web.Auth(
session=session,
authority="https://login.microsoftonline.com/common",
client_id="your_app_client_id",
client_credential="your_secret",
)
```
--------------------------------
### Flask Session Configuration
Source: https://github.com/rayluo/identity/blob/dev/docs/flask.rst
Configures Flask-Session to store session data in the filesystem. This is a common setup for development or simpler deployments.
```python
# Tells the Flask-session extension to store sessions in the filesystem
SESSION_TYPE = "filesystem"
```
--------------------------------
### Initialize Identity Auth in Quart App
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Demonstrates how to create an instance of the `identity.quart.Auth` object within a Quart application's main file (`app.py`). It shows how to pass configuration parameters like `CLIENT_ID`, `CLIENT_SECRET`, and `REDIRECT_URI`.
```python
import os
from quart import Quart
from identity.quart import Auth
app = Quart(__name__)
auth = Auth(
app,
# Instruction for these settings is available in this project's README file.
# https://github.com/rayluo/identity?tab=readme-ov-file#scenarios-supported
os.getenv('CLIENT_ID'),
client_credential=os.getenv('CLIENT_SECRET'),
redirect_uri=
# Recommended to register and use a redirect_uri.
# It looks like http://localhost:5000/redirect for local development,
# or https://your_website.com/redirect for your production.
# If absent, Identity library will fall back to a Device Code mode.
os.getenv('REDIRECT_URI'),
..., # See below on how to feed in the authority url parameter
)
```
--------------------------------
### Add Identity to INSTALLED_APPS
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Enables the Identity package's default templates and functionalities by adding 'identity' to the INSTALLED_APPS list in settings.py.
```python
INSTALLED_APPS = [
...,
"identity",
]
```
--------------------------------
### Identity Web Auth Class Initialization and Usage
Source: https://github.com/rayluo/identity/blob/dev/docs/generic.rst
Demonstrates how to create an instance of the Auth class and use its methods for web application user login flows. It covers initiating login, completing the login process, and logging out users.
```APIDOC
identity.web.Auth
__init__(session, authority, client_id, client_credential)
Initializes the Auth object for web application authentication.
Parameters:
session: A session object providing key-value storage with a dict-like interface. Many web frameworks provide this.
authority: The authority URL for authentication, e.g., "https://login.microsoftonline.com/common".
client_id: The client ID of your application.
client_credential: The secret credential for your application.
log_in(scopes, redirect_uri)
Initiates the user login process.
Parameters:
scopes: A list of strings representing the requested scopes, e.g., ["your_scope"].
redirect_uri: The URI to which the user will be redirected after authentication, e.g., "https://your_app.example.com/redirect_uri".
Returns:
A tuple containing the authentication URI (auth_uri) and optionally a user code (user_code).
Usage:
Call this method in your web app's login controller to obtain auth_uri and user_code, then render them in your login HTML page.
complete_log_in(incoming_query_parameters)
Completes the user login process after the user has been redirected back to the application.
Parameters:
incoming_query_parameters: The query parameters received in the redirect request.
Returns:
A dictionary containing user information. If an 'error' key is present, authentication failed. Otherwise, user information is available.
Usage:
Implement this in a separate controller that handles the redirect. If successful, user details (including 'sub' for unique ID) are available.
get_user()
Retrieves the logged-in user's information.
Usage:
Call this method on the dictionary returned by complete_log_in to get user details.
log_out(redirect_uri)
Logs the user out.
Parameters:
redirect_uri: The URI to redirect the user to after logout, e.g., "https://your_app.example.com".
Returns:
Details about the logout process (refer to specific method docs for return value).
get_token_for_user(scopes)
Obtains an access token for the user to call a web API on their behalf.
Parameters:
scopes: A list of strings representing the requested scopes for the token.
Returns:
A token object (details depend on implementation).
Usage:
Call this after a successful login to acquire tokens for API access.
```
--------------------------------
### Project Dependencies (requirements.txt)
Source: https://github.com/rayluo/identity/blob/dev/requirements.txt
Lists the project dependencies specified in the requirements.txt file. It includes the main project package with all documentation extras, and testing tools like pytest and pytest-asyncio.
```Shell
-e .[all_for_docs]
pytest
pytest-asyncio
```
--------------------------------
### Configure Identity Auth in settings.py
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Sets up the Identity Auth object in Django's settings.py. It requires client ID, secret, and redirect URI, typically loaded from environment variables.
```python
import os
from dotenv import load_dotenv
from identity.django import Auth
load_dotenv()
AUTH = Auth(
os.getenv('CLIENT_ID'),
client_credential=os.getenv('CLIENT_SECRET'),
redirect_uri=os.getenv('REDIRECT_URI'),
# ... authority url parameter
)
```
--------------------------------
### Initialize Auth Object for Identity Providers
Source: https://github.com/rayluo/identity/blob/dev/docs/auth.rst
Demonstrates how to initialize the Auth object with specific parameters tailored to different identity provider types. This includes using 'authority' for Microsoft Entra ID, 'oidc_authority' for Entra External ID with custom domains, and 'b2c_tenant_name' with 'b2c_signup_signin_user_flow' for Azure AD B2C.
```python
from auth_library import Auth
# Microsoft Entra ID
url_entra = "https://login.microsoftonline.com/tenant"
auth_entra = Auth(..., authority=url_entra, ...)
# Microsoft Entra External ID with Custom Domain
url_external_custom = "https://contoso.com/tenant"
auth_external_custom = Auth(..., oidc_authority=url_external_custom, ...)
# Azure AD B2C
auth_b2c = Auth(..., b2c_tenant_name="contoso", b2c_signup_signin_user_flow="susi")
```
--------------------------------
### Jinja Authentication Template Structure
Source: https://github.com/rayluo/identity/blob/dev/identity/templates/identity/login.html
This Jinja template defines the structure for an authentication page, handling conditional display of sign-in instructions or password reset links based on context variables. It supports dynamic content insertion via Jinja variables.
```Jinja
{# The default template uses only a common subset of Django and Flask syntax. #} {# See also https://jinja.palletsprojects.com/en/latest/switching/#django #} {# But, your project probably runs on a specific web framework exclusively, #} {# so, your customized template may use all syntax of your chosen framework. #} {% if user_code or reset_password_url %} Sign In
Sign In
=======
{% if user_code %}
1. To sign in, type **{{ user_code }}** into [{{ auth_uri }}]({{ auth_uri }}) to authenticate.
2. And then [proceed]({{ auth_response_url }}).
{% else %}
* [Sign In]({{ auth_uri }})
{% endif %} {% if reset_password_url %}
* * *
[Reset Password]({{ reset_password_url }}) {% endif %} {% else %} {% endif %}
```
--------------------------------
### Initialize Identity Auth in Flask App
Source: https://github.com/rayluo/identity/blob/dev/docs/flask.rst
Creates an instance of the identity.flask.Auth object and configures it with application settings and environment variables for client ID, secret, and redirect URI.
```python
import os
from flask import Flask
from identity.flask import Auth
import app_config
app = Flask(__name__)
app.config.from_object(app_config)
auth = Auth(
app,
# Instruction for these settings is available in this project's README file.
# https://github.com/rayluo/identity?tab=readme-ov-file#scenarios-supported
os.getenv('CLIENT_ID'),
client_credential=os.getenv('CLIENT_SECRET'),
redirect_uri=
# Recommended to register and use a redirect_uri.
# It looks like http://localhost:5000/redirect for local development,
# or https://your_website.com/redirect for your production.
# If absent, Identity library will fall back to a Device Code mode.
os.getenv('REDIRECT_URI'),
..., # See below on how to feed in the authority url parameter
)
```
--------------------------------
### Configure Redis Session Store for Quart
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Configures the Quart application to use Redis as the session store. This involves setting the `SESSION_TYPE` and `SESSION_URI` configuration variables.
```python
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_URI'] = 'redis://localhost:6379'
```
--------------------------------
### Include Identity URLs in urls.py
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Integrates the Identity library's URL patterns into your Django project's main urls.py, allowing access to built-in views like logout.
```python
from django.conf import settings
urlpatterns = [
settings.AUTH.urlpattern,
...
]
```
--------------------------------
### Identity Django Auth Class API
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Documentation for the identity.django.Auth class, detailing its constructor and methods for managing authentication flows in Django applications.
```apidoc
class identity.django.Auth:
"""Manages authentication flows for Django applications."""
__init__(client_id: str, client_credential: str = None, redirect_uri: str = None, authority: str = None, **kwargs):
"""Initializes the Auth object.
Args:
client_id: The client ID obtained from the identity provider.
client_credential: The client secret or certificate for authentication.
redirect_uri: The URI to redirect to after authentication. If absent, device code flow is used.
authority: The authority URL for the identity provider.
**kwargs: Additional keyword arguments for configuration.
"""
pass
login_required(scopes: list = None):
"""Decorator to protect views, ensuring the user is authenticated.
Args:
scopes: A list of OAuth scopes required for accessing resources.
Returns:
A decorator function.
"""
pass
urlpattern: django.urls.path:
"""Provides the URL pattern for built-in Identity views, such as logout."""
pass
logout(request):
"""Handles the logout process for the user."""
pass
# Inherited members from base Auth class might include methods for token acquisition, refresh, etc.
# Example: get_token(scopes: list = None)
# Example: get_user_info()
```
--------------------------------
### Add Logout Link in Quart Template
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Provides the HTML snippet to create a logout link within a Quart template. The link points to the `identity.logout` endpoint, which handles user sign-out.
```html
Logout
```
--------------------------------
### Call Web API with Scopes in Quart
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Demonstrates how to protect a Quart route that calls an external web API. The `login_required` decorator is used with specific `scopes`, and the `access_token` is retrieved from the context to be used in API requests via `httpx`.
```python
@app.route("/call_api")
@auth.login_required(scopes=["your_scope_1", "your_scope_2"])
async def call_api(*, context):
async with httpx.AsyncClient() as client:
api_result = await client.get( # Use access token to call a web api
os.getenv("ENDPOINT"),
headers={'Authorization': 'Bearer ' + context['access_token']},
)
return await render_template('display.html', result=api_result)
```
--------------------------------
### Call Web API with Access Token
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Secures a view that calls an external web API. The login_required decorator fetches an access token with specified scopes, available in the view context.
```python
import requests
from django.conf import settings
@settings.AUTH.login_required(scopes=["your_scope"])
def call_api(request, *, context):
api_result = requests.get(
"https://your_api.example.com",
headers={'Authorization': 'Bearer ' + context['access_token']},
timeout=30,
).json()
...
```
--------------------------------
### Logout Link in Template
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Provides a standard HTML anchor tag with a Django URL tag to generate the logout link, allowing users to sign out of the application.
```html
Logout
```
--------------------------------
### Call Web API with Access Token
Source: https://github.com/rayluo/identity/blob/dev/docs/flask.rst
Decorates a Flask view to require authentication and obtain an access token. The token is then used in the Authorization header to call a protected web API.
```python
@app.route("/call_api")
@auth.login_required(scopes=["your_scope_1", "your_scope_2"])
def call_api(*, context):
api_result = requests.get( # Use access token to call a web api
"https://your_api.example.com",
headers={'Authorization': 'Bearer ' + context['access_token']},
timeout=30,
)
...
```
--------------------------------
### Logout Link in Flask Template
Source: https://github.com/rayluo/identity/blob/dev/docs/flask.rst
Provides an HTML anchor tag that links to the identity logout route, allowing users to sign out of the application.
```html
Logout
```
--------------------------------
### Protect Views with Login Required
Source: https://github.com/rayluo/identity/blob/dev/docs/django.rst
Secures Django views by decorating them with the login_required decorator from the Identity Auth object. It injects user context into the view.
```python
from django.conf import settings
from django.http import HttpResponse
@settings.AUTH.login_required
def index(request, *, context):
user = context['user']
return HttpResponse(f"Hello, {user.get('name')}.")
```
--------------------------------
### Conditional Auth Error Display in Jinja Template
Source: https://github.com/rayluo/identity/blob/dev/identity/templates/identity/auth_error.html
This snippet demonstrates conditional logic in a Jinja/Django template to display specific error messages based on the presence of reset password URLs and error descriptions, particularly for Azure AD B2C error code AADB2C90118. It checks for the existence of `reset_password_url` and `error_description`, and if a specific error code is present in the description, it proceeds with rendering error details.
```Jinja
{# The template uses only a common subset of Django and Flask syntax. #} {# See also https://jinja.palletsprojects.com/en/latest/switching/#django #} {% if reset_password_url and error_description and "AADB2C90118" in error_description %} {% endif %}
```
--------------------------------
### Protect Quart Route with Login Requirement
Source: https://github.com/rayluo/identity/blob/dev/docs/quart.rst
Applies the `login_required` decorator to a Quart view function. This decorator automatically triggers the sign-in process if the user is not authenticated.
```python
@app.route("/")
@auth.login_required
async def index(*, context):
user = context['user']
...
```
--------------------------------
### Protect Flask View with Login Required
Source: https://github.com/rayluo/identity/blob/dev/docs/flask.rst
Applies the login_required decorator to a Flask view function. If the user is not authenticated, it triggers the sign-in flow.
```python
@app.route("/")
@auth.login_required
def index(*, context):
user = context['user']
...
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.