1
1
import pytest
2
+ from fastapi import APIRouter
3
+ from fastapi import Depends
2
4
from fastapi import FastAPI
5
+ from fastapi import Request
3
6
from httpx import AsyncClient
4
7
from social_core .backends .github import GithubOAuth2
8
+ from starlette .responses import Response
5
9
6
10
from fastapi_oauth2 .client import OAuth2Client
7
11
from fastapi_oauth2 .core import OAuth2Core
8
12
from fastapi_oauth2 .middleware import OAuth2Middleware
9
13
from fastapi_oauth2 .router import router as oauth2_router
14
+ from fastapi_oauth2 .security import OAuth2
10
15
11
16
app = FastAPI ()
17
+ oauth2 = OAuth2 ()
18
+ app_router = APIRouter ()
12
19
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 )
13
45
app .include_router (oauth2_router )
14
46
app .add_middleware (OAuth2Middleware , config = {
15
47
"allow_http" : True ,
@@ -30,6 +62,18 @@ async def test_auth_redirect():
30
62
assert response .status_code == 303 # Redirect
31
63
32
64
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
+
33
77
@pytest .mark .anyio
34
78
async def test_core_init (backends ):
35
79
for backend in backends :
0 commit comments