oauth-2.0 使用fastapi的python oath2示例

bqf10yzr  于 2022-10-31  发布在  Python
关注(0)|答案(1)|浏览(194)

我在这个网站上找到了一个例子,https://blog.hanchon.live/guides/google-login-with-fastapi/
是否有类似Microsoft AD身份验证示例?

import os
import starlette
from starlette.config import Config
from authlib.integrations.starlette_client import OAuth

# OAuth settings

GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID') or None
GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET') or None
if GOOGLE_CLIENT_SECRET is None or GOOGLE_CLIENT_ID is None:
    raise BaseException('Missing env variables')

# setup OAuth

config_data = {'GOOGLE_CLIENT_ID': GOOGLE_CLIENT_ID,
               'GOOGLE_CLIENT_SECRET': GOOGLE_CLIENT_SECRET}
starlette_config = Config(environ=config_data)
oauth = OAuth(starlette_config)
oauth.register(
    name='google',
    server_metada_url='https://accounts.google.com/.well-known/openid-configuration',
    client_kwargs={'scope': 'openid email profile'}
)

输出为:]在示例['id']上:'10'指定的JSON数据是无效的回溯(最后呼叫最近的):文件sample3.py“/应用程序/www.example.com“,第337行,Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/json/init.pyXcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/json/decoder.py在解码对象中,end = self.raw_decode(s,idx=_w(s,0).end())文件“/应用程序/www.example.com“,第353行,在解码对象Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/json/decoder.py中,原始解码中]
用户模式为:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "User",
  "description": "A user request json",
  "type": "object",
  "properties": {
    "id": {
      "description": "The unique identifier for a user",
      "type": "integer"
    },
    "name": {
      "description": "Name of the user",
      "type": "string"
    },
    "contact_number": {
      "type": "number"
    }
  },
  "required": ["id", "name", "contact_number"]
}
brc7rcf0

brc7rcf01#

来自github的示例:

import json
from fastapi import FastAPI
from starlette.config import Config
from starlette.requests import Request
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import HTMLResponse, RedirectResponse
from authlib.integrations.starlette_client import OAuth, OAuthError

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="!secret")

config = Config('.env')
oauth = OAuth(config)

CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'
oauth.register(
    name='google',
    server_metadata_url=CONF_URL,
    client_kwargs={
        'scope': 'openid email profile'
    }
)

@app.get('/')
async def homepage(request: Request):
    user = request.session.get('user')
    if user:
        data = json.dumps(user)
        html = (
            f'<pre>{data}</pre>'
            '<a href="/logout">logout</a>'
        )
        return HTMLResponse(html)
    return HTMLResponse('<a href="/login">login</a>')

@app.get('/login')
async def login(request: Request):
    redirect_uri = request.url_for('auth')
    return await oauth.google.authorize_redirect(request, redirect_uri)

@app.get('/auth')
async def auth(request: Request):
    try:
        token = await oauth.google.authorize_access_token(request)
    except OAuthError as error:
        return HTMLResponse(f'<h1>{error.error}</h1>')
    user = token.get('userinfo')
    if user:
        request.session['user'] = dict(user)
    return RedirectResponse(url='/')

@app.get('/logout')
async def logout(request: Request):
    request.session.pop('user', None)
    return RedirectResponse(url='/')

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='127.0.0.1', port=8000)

相关问题