11import pytest
2+ from fastapi import APIRouter
3+ from fastapi import Depends
24from fastapi import FastAPI
5+ from fastapi import Request
36from httpx import AsyncClient
47from social_core .backends .github import GithubOAuth2
8+ from starlette .responses import Response
59
610from fastapi_oauth2 .client import OAuth2Client
711from fastapi_oauth2 .core import OAuth2Core
812from fastapi_oauth2 .middleware import OAuth2Middleware
913from fastapi_oauth2 .router import router as oauth2_router
14+ from fastapi_oauth2 .security import OAuth2
1015
1116app = FastAPI ()
17+ oauth2 = OAuth2 ()
18+ app_router = APIRouter ()
1219
20+
21+ @app_router .get ("/user" )
22+ def user (request : Request , _ : str = Depends (oauth2 )):
23+ return request .user
24+
25+
26+ @app_router .get ("/auth" )
27+ def auth (request : Request ):
28+ access_token = request .auth .jwt_create ({
29+ "name" : "test" ,
30+ "sub" : "test" ,
31+ "id" : "test" ,
32+ })
33+ response = Response ()
34+ response .set_cookie (
35+ "Authorization" ,
36+ value = f"Bearer { access_token } " ,
37+ max_age = request .auth .expires ,
38+ expires = request .auth .expires ,
39+ httponly = request .auth .http ,
40+ )
41+ return response
42+
43+
44+ app .include_router (app_router )
1345app .include_router (oauth2_router )
1446app .add_middleware (OAuth2Middleware , config = {
1547 "allow_http" : True ,
@@ -30,6 +62,18 @@ async def test_auth_redirect():
3062 assert response .status_code == 303 # Redirect
3163
3264
65+ @pytest .mark .anyio
66+ async def test_authenticated_request ():
67+ async with AsyncClient (app = app , base_url = "http://test" ) as client :
68+ response = await client .get ("/user" )
69+ assert response .status_code == 403 # Forbidden
70+
71+ await client .get ("/auth" ) # Simulate login
72+
73+ response = await client .get ("/user" )
74+ assert response .status_code == 200 # OK
75+
76+
3377@pytest .mark .anyio
3478async def test_core_init (backends ):
3579 for backend in backends :
0 commit comments