## OAuthAzureFastApi
### Simple and Effective Azure OAuth2 Integration for FastAPI
OAuthAzureFastApi is a streamlined Python package that empowers you to seamlessly integrate Azure Active Directory (AAD) authentication into your FastAPI applications. It streamlines the OAuth2 flow, providing a straightforward approach to secure your API routes with Azure AD credentials.
### Requirements
- **ID Token Flow:** Ensure it's enabled under `Manage > Authentication` within your Azure App Registration.
- **User.Read Permission:** Grant this permission for Microsoft Graph access under `API Permissions`.
### Installation
Utilize pip to install the package:
```bash
pip install oauthAzureFastApi
Usage
Example FastAPI Application
This code snippet demonstrates how to establish your FastAPI application for leveraging OAuthAzureFastApi:
from fastapi import FastAPI, Depends, Request
from starlette.middleware.sessions import SessionMiddleware
from oauthAzureFastApi import OAuthApp
# Replace with your Azure AD credentials
client_id = "your-client-id"
client_secret = "your-client-secret"
tenant_id = "your-tenant-id"
redirect_uri = "http://localhost:8000/callback"
frontend_uri= "http://127.0.0.1:5500/"
# Create the OAuth app instance
oauth_app = OAuthApp(client_id, client_secret, tenant_id, redirect_uri,frontend_uri)
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="your-session-secret")
# Integrate the OAuth router
app.include_router(oauth_app.get_app(), prefix="")
# Secure API Endpoints using the get_current_user_from_app dependency
async def get_current_user_from_app(request: Request):
return await oauth_app.get_current_user(request)
# Example of a secured endpoint
@app.get("/secure-data")
async def secure_data(user: dict = Depends(get_current_user_from_app)):
"""Endpoint for accessing secure data."""
return {"message": "Secure data accessed", "user": user}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
```
### Example Login and Token Refresh
Once your application is running, you can effortlessly access these pre-built endpoints:
### Login URL:
Navigate to http://localhost:8000/login in your web browser to initiate login using Microsoft Single Sign-On (SSO). Upon successful login, this endpoint will provide you with access_token,refresh_token and userdetails.
### Token Refresh URL:
Employ the POST endpoint http://localhost:8000/refresh-id-token to refresh the ID token. Transmit the refresh_token as a query parameter.
Example:
POST http://localhost:8000/refresh-id-token?refresh_token=<your-refresh-token>
### Securing Endpoints
To safeguard your FastAPI endpoints, incorporate the get_current_user_from_app function as a dependency. This ensures user authentication before accessing the endpoint. You can also access all user realated detail from the user parameter.
```bash
@app.get("/secure-data")
async def secure_data(user: dict = Depends(get_current_user_from_app)):
return {"message": "Secure data accessed", "user": user}
```
By including this dependency, only authorized users possessing a valid Azure AD token will be granted access to the endpoint.
### Example frontend code to extract the access token,refresh token and user info in frontend
```bash
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OAuth2 Test App</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
h1 {
color: #333;
}
.tokens {
margin-top: 20px;
text-align: left;
}
pre {
background-color: #f4f4f4;
padding: 15px;
border: 1px solid #ddd;
}
#loginBtn {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
#loginBtn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h1>Login with OAuth</h1>
<p>Click the button below to login:</p>
<button id="loginBtn">Login with OAuth</button>
<div id="tokenContainer" style="display:none;">
<h3>Tokens</h3>
<p><strong>Access Token:</strong> <span id="accessToken"></span></p>
<p><strong>Refresh Token:</strong> <span id="refreshToken"></span></p>
<p><strong>Session ID:</strong> <span id="sessionId"></span></p>
<h3>User Info</h3>
<p><strong>User ID:</strong> <span id="userId"></span></p>
<p><strong>Email:</strong> <span id="userEmail"></span></p>
<p><strong>Name:</strong> <span id="userName"></span></p>
<p><strong>Role:</strong> <span id="userRole"></span></p>
</div>
</div>
<script>
// Handle page load to extract tokens from the URL fragment
window.onload = function() {
const hash = window.location.hash;
if (hash) {
const params = new URLSearchParams(hash.substring(1)); // Remove '#'
const accessToken = params.get('access_token');
const refreshToken = params.get('refresh_token');
const sessionId = params.get('session_id');
const userInfo = params.get('user_info');
if (accessToken && refreshToken && sessionId && userInfo) {
// Display tokens
document.getElementById('accessToken').innerText = accessToken;
document.getElementById('refreshToken').innerText = refreshToken;
document.getElementById('sessionId').innerText = sessionId;
// Parse user_info JSON string and display user details
const user = JSON.parse(decodeURIComponent(userInfo));
document.getElementById('userId').innerText = user.user_id;
document.getElementById('userEmail').innerText = user.email;
document.getElementById('userName').innerText = user.name;
document.getElementById('userRole').innerText = user.role.join(', '); // Display role as comma-separated list
document.getElementById('tokenContainer').style.display = 'block';
}
}
};
// Simulate a login flow (you should replace the URL with your backend's login endpoint)
document.getElementById('loginBtn').onclick = function() {
// Redirect to your backend login route
window.location.href = "http://localhost:8000/login"; // Change to your backend login route
};
</script>
</body>
</html>
```
// Simulate a login flow (you should replace the URL with your backend's login endpoint)
document.getElementById('loginBtn').onclick = function() {
// This would redirect to your backend login route
window.location.href = "http://localhost:8000/login"; // Change to your backend login route
};
</script>
</body>
</html>
### Conclusion
OAuthAzureFastApi simplifies the integration of Azure AD authentication within your FastAPI applications, offering a swift and efficient method to secure your routes. Follow the steps above to quickly implement authentication in your FastAPI application.
Raw data
{
"_id": null,
"home_page": "https://github.com/saubhik1/oauthAzureFastApi",
"name": "oauthAzureFastApi",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": null,
"author": "Saubhik Bhadra,Kaushik Bhadra",
"author_email": "saubhik.bhadra@gmail.com,kaushik.bhadra24@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/1f/28/e308d0d47220be1031877307b6ac760470d7a503950e41bdbed75c0c1f4f/oauthazurefastapi-0.4.16.tar.gz",
"platform": null,
"description": "## OAuthAzureFastApi\r\n\r\n### Simple and Effective Azure OAuth2 Integration for FastAPI\r\n\r\nOAuthAzureFastApi is a streamlined Python package that empowers you to seamlessly integrate Azure Active Directory (AAD) authentication into your FastAPI applications. It streamlines the OAuth2 flow, providing a straightforward approach to secure your API routes with Azure AD credentials.\r\n\r\n### Requirements\r\n\r\n- **ID Token Flow:** Ensure it's enabled under `Manage > Authentication` within your Azure App Registration.\r\n- **User.Read Permission:** Grant this permission for Microsoft Graph access under `API Permissions`.\r\n\r\n### Installation\r\n\r\nUtilize pip to install the package:\r\n\r\n```bash\r\npip install oauthAzureFastApi\r\n\r\n\r\nUsage\r\nExample FastAPI Application\r\nThis code snippet demonstrates how to establish your FastAPI application for leveraging OAuthAzureFastApi:\r\n\r\n\r\nfrom fastapi import FastAPI, Depends, Request\r\nfrom starlette.middleware.sessions import SessionMiddleware\r\nfrom oauthAzureFastApi import OAuthApp\r\n\r\n# Replace with your Azure AD credentials\r\nclient_id = \"your-client-id\"\r\nclient_secret = \"your-client-secret\"\r\ntenant_id = \"your-tenant-id\"\r\nredirect_uri = \"http://localhost:8000/callback\"\r\nfrontend_uri= \"http://127.0.0.1:5500/\" \r\n\r\n# Create the OAuth app instance\r\noauth_app = OAuthApp(client_id, client_secret, tenant_id, redirect_uri,frontend_uri)\r\n\r\napp = FastAPI()\r\napp.add_middleware(SessionMiddleware, secret_key=\"your-session-secret\")\r\n\r\n# Integrate the OAuth router\r\napp.include_router(oauth_app.get_app(), prefix=\"\")\r\n\r\n# Secure API Endpoints using the get_current_user_from_app dependency\r\nasync def get_current_user_from_app(request: Request):\r\n return await oauth_app.get_current_user(request)\r\n\r\n# Example of a secured endpoint\r\n@app.get(\"/secure-data\")\r\nasync def secure_data(user: dict = Depends(get_current_user_from_app)):\r\n \"\"\"Endpoint for accessing secure data.\"\"\"\r\n return {\"message\": \"Secure data accessed\", \"user\": user}\r\n\r\nif __name__ == \"__main__\":\r\n import uvicorn\r\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\r\n\r\n```\r\n### Example Login and Token Refresh\r\nOnce your application is running, you can effortlessly access these pre-built endpoints:\r\n\r\n### Login URL:\r\n\r\nNavigate to http://localhost:8000/login in your web browser to initiate login using Microsoft Single Sign-On (SSO). Upon successful login, this endpoint will provide you with access_token,refresh_token and userdetails.\r\n\r\n### Token Refresh URL:\r\n\r\nEmploy the POST endpoint http://localhost:8000/refresh-id-token to refresh the ID token. Transmit the refresh_token as a query parameter.\r\n\r\nExample:\r\n\r\nPOST http://localhost:8000/refresh-id-token?refresh_token=<your-refresh-token>\r\n\r\n\r\n### Securing Endpoints\r\nTo safeguard your FastAPI endpoints, incorporate the get_current_user_from_app function as a dependency. This ensures user authentication before accessing the endpoint. You can also access all user realated detail from the user parameter.\r\n\r\n```bash\r\n@app.get(\"/secure-data\")\r\nasync def secure_data(user: dict = Depends(get_current_user_from_app)):\r\n return {\"message\": \"Secure data accessed\", \"user\": user}\r\n```\r\n\r\nBy including this dependency, only authorized users possessing a valid Azure AD token will be granted access to the endpoint.\r\n\r\n### Example frontend code to extract the access token,refresh token and user info in frontend\r\n\r\n```bash\r\n<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>OAuth2 Test App</title>\r\n <style>\r\n body {\r\n font-family: Arial, sans-serif;\r\n margin: 20px;\r\n }\r\n .container {\r\n max-width: 600px;\r\n margin: auto;\r\n text-align: center;\r\n }\r\n h1 {\r\n color: #333;\r\n }\r\n .tokens {\r\n margin-top: 20px;\r\n text-align: left;\r\n }\r\n pre {\r\n background-color: #f4f4f4;\r\n padding: 15px;\r\n border: 1px solid #ddd;\r\n }\r\n #loginBtn {\r\n padding: 10px 20px;\r\n background-color: #4CAF50;\r\n color: white;\r\n border: none;\r\n border-radius: 5px;\r\n cursor: pointer;\r\n font-size: 16px;\r\n }\r\n #loginBtn:hover {\r\n background-color: #45a049;\r\n }\r\n </style>\r\n</head>\r\n<body>\r\n\r\n <div class=\"container\">\r\n <h1>Login with OAuth</h1>\r\n <p>Click the button below to login:</p>\r\n <button id=\"loginBtn\">Login with OAuth</button>\r\n\r\n <div id=\"tokenContainer\" style=\"display:none;\">\r\n <h3>Tokens</h3>\r\n <p><strong>Access Token:</strong> <span id=\"accessToken\"></span></p>\r\n <p><strong>Refresh Token:</strong> <span id=\"refreshToken\"></span></p>\r\n <p><strong>Session ID:</strong> <span id=\"sessionId\"></span></p>\r\n \r\n <h3>User Info</h3>\r\n <p><strong>User ID:</strong> <span id=\"userId\"></span></p>\r\n <p><strong>Email:</strong> <span id=\"userEmail\"></span></p>\r\n <p><strong>Name:</strong> <span id=\"userName\"></span></p>\r\n <p><strong>Role:</strong> <span id=\"userRole\"></span></p>\r\n </div>\r\n </div>\r\n\r\n<script>\r\n // Handle page load to extract tokens from the URL fragment\r\n window.onload = function() {\r\n const hash = window.location.hash;\r\n if (hash) {\r\n const params = new URLSearchParams(hash.substring(1)); // Remove '#'\r\n const accessToken = params.get('access_token');\r\n const refreshToken = params.get('refresh_token');\r\n const sessionId = params.get('session_id');\r\n const userInfo = params.get('user_info');\r\n \r\n if (accessToken && refreshToken && sessionId && userInfo) {\r\n // Display tokens\r\n document.getElementById('accessToken').innerText = accessToken;\r\n document.getElementById('refreshToken').innerText = refreshToken;\r\n document.getElementById('sessionId').innerText = sessionId;\r\n\r\n // Parse user_info JSON string and display user details\r\n const user = JSON.parse(decodeURIComponent(userInfo));\r\n document.getElementById('userId').innerText = user.user_id;\r\n document.getElementById('userEmail').innerText = user.email;\r\n document.getElementById('userName').innerText = user.name;\r\n document.getElementById('userRole').innerText = user.role.join(', '); // Display role as comma-separated list\r\n\r\n document.getElementById('tokenContainer').style.display = 'block';\r\n }\r\n }\r\n };\r\n\r\n // Simulate a login flow (you should replace the URL with your backend's login endpoint)\r\n document.getElementById('loginBtn').onclick = function() {\r\n // Redirect to your backend login route\r\n window.location.href = \"http://localhost:8000/login\"; // Change to your backend login route\r\n };\r\n</script>\r\n\r\n</body>\r\n</html>\r\n```\r\n // Simulate a login flow (you should replace the URL with your backend's login endpoint)\r\n document.getElementById('loginBtn').onclick = function() {\r\n // This would redirect to your backend login route\r\n window.location.href = \"http://localhost:8000/login\"; // Change to your backend login route\r\n };\r\n</script>\r\n\r\n</body>\r\n</html>\r\n\r\n### Conclusion\r\nOAuthAzureFastApi simplifies the integration of Azure AD authentication within your FastAPI applications, offering a swift and efficient method to secure your routes. Follow the steps above to quickly implement authentication in your FastAPI application.\r\n",
"bugtrack_url": null,
"license": null,
"summary": "A FastAPI module for Azure OAuth integration",
"version": "0.4.16",
"project_urls": {
"Homepage": "https://github.com/saubhik1/oauthAzureFastApi"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "16ca059cbcbadf44e6d29dd48a1c15fc542558da8b869d1958ab842d13a47ec9",
"md5": "8e06639b8c32675b40520c3508c385f2",
"sha256": "73b411b12f18a0921a99511ac96270b751572432c5abf895e7284a78057f9854"
},
"downloads": -1,
"filename": "oauthAzureFastApi-0.4.16-py3-none-any.whl",
"has_sig": false,
"md5_digest": "8e06639b8c32675b40520c3508c385f2",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 6413,
"upload_time": "2024-09-11T06:48:18",
"upload_time_iso_8601": "2024-09-11T06:48:18.049028Z",
"url": "https://files.pythonhosted.org/packages/16/ca/059cbcbadf44e6d29dd48a1c15fc542558da8b869d1958ab842d13a47ec9/oauthAzureFastApi-0.4.16-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "1f28e308d0d47220be1031877307b6ac760470d7a503950e41bdbed75c0c1f4f",
"md5": "692fbad00f08f5ad04df94413d92aa87",
"sha256": "e328cae288bdd6c8210120a95119e78480ef2d2bb7fdf6ba06b662d82dc526e1"
},
"downloads": -1,
"filename": "oauthazurefastapi-0.4.16.tar.gz",
"has_sig": false,
"md5_digest": "692fbad00f08f5ad04df94413d92aa87",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 6505,
"upload_time": "2024-09-11T06:48:23",
"upload_time_iso_8601": "2024-09-11T06:48:23.330689Z",
"url": "https://files.pythonhosted.org/packages/1f/28/e308d0d47220be1031877307b6ac760470d7a503950e41bdbed75c0c1f4f/oauthazurefastapi-0.4.16.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-11 06:48:23",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "saubhik1",
"github_project": "oauthAzureFastApi",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "oauthazurefastapi"
}