社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python Flask msal示例应用程序移植到FastAPI

Richard • 4 年前 • 2135 次点击  

我没有做太多的网络工作,但我最近开始使用FastAPI,并正在使用jinja2模板构建一个MVC应用程序,该应用程序使用PowerBI嵌入式功能在应用程序中提供多个嵌入式分析数据。所有这些都很好地发挥了作用。然而,我想添加更多的模块,我想使用msal包来进行用户身份验证,方法是将用户路由到Microsoft登录页面,让他们登录我在Azure中设置的多租户应用程序服务,然后通过重定向URI重定向回我的页面,获取令牌,并进行授权。微软为我们保存了一个很好的例子 here 在烧瓶里做这件事。然而,我在将示例移植到FastAPI时遇到了麻烦。

我可以让用户进入登录屏幕并登录,但我无法在回拨URI中捕获令牌——这是正确的路由,但我无法从响应中捕获令牌。

有没有人(或者有人能)把这个超级简单的烧瓶示例移植到FastAPI?我在FAPI网上找到的所有东西都是API的后端令牌承载头,而不是MVC应用。

这是我目前的代码。混乱是因为我有内置的“测试”。

import msal
import requests
from fastapi import APIRouter, Request, Response
from fastapi.responses import RedirectResponse
from starlette.templating import Jinja2Templates

from config import get_settings

settings = get_settings()
router = APIRouter()
templates = Jinja2Templates('templates')


# Works
@router.get('/login', include_in_schema=False)
async def login(request: Request):
    request.session['flow'] = _build_auth_code_flow(scopes=settings.AUTH_SCOPE)
    login_url = request.session['flow']['auth_uri']
    return templates.TemplateResponse('error.html', {'request': request, 'message': login_url})


# DOES NOT WORK - Pretty sure error is in here --------------------
@router.get('/getAToken', response_class=Response, include_in_schema=False)
async def authorize(request: Request):
    try:
        cache = _load_cache(request)
        result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow(
            request.session.get('flow'), request.session
        )
        if 'error' in result:
            return templates.TemplateResponse('error.html', {'request': request, 'message': result})
        request.session['user'] = result.get('id_token_claims')
        _save_cache(cache)
    except Exception as error:
        return templates.TemplateResponse('error.html', {'request': request, 'message': f'{error}: {str(request.query_params)}'})
    return templates.TemplateResponse('error.html', {'request': request, 'message': result})
# -----------------------------------------------------

    
def _load_cache(request: Request):
    cache = msal.SerializableTokenCache()
    if request.session.get("token_cache"):
        cache.deserialize(request.session["token_cache"])
    return cache


def _save_cache(request: Request, cache):
    if cache.has_state_changed:
        request.session["token_cache"] = cache.serialize()


def _build_msal_app(cache=None, authority=None):
    return msal.ConfidentialClientApplication(
        settings.CLIENT_ID,
        authority=authority or settings.AUTH_AUTHORITY,
        client_credential=settings.CLIENT_SECRET,
        token_cache=cache
    )


def _build_auth_code_flow(authority=None, scopes=None):
    return _build_msal_app(authority=authority).initiate_auth_code_flow(
        scopes or [],
        redirect_uri=settings.AUTH_REDIRECT)


def _get_token_from_cache(scope=None):
    cache = _load_cache()  # This web app maintains one cache per session
    cca = _build_msal_app(cache=cache)
    accounts = cca.get_accounts()
    if accounts:  # So all account(s) belong to the current signed-in user
        result = cca.acquire_token_silent(scope, account=accounts[0])
        _save_cache(cache)
        return result

非常感谢您的帮助。乐意回答任何问题。非常感谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130921
文章 [ 1 ]  |  最新文章 4 年前