Skip to content

Commit c269911

Browse files
committed
GH-7: Implement a cookie supporting OAuth2 security classes
1 parent 8bc7781 commit c269911

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/fastapi_oauth2/security.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from fastapi.security import OAuth2 as FastAPIOAuth2
2+
from fastapi.security import OAuth2AuthorizationCodeBearer as FastAPICodeBearer
3+
from fastapi.security import OAuth2PasswordBearer as FastAPIPasswordBearer
4+
from starlette.datastructures import Headers
5+
from starlette.requests import Request
6+
7+
8+
def use_cookie(cls: FastAPIOAuth2):
9+
def _use_cookie(*args, **kwargs):
10+
async def __call__(self, request: Request):
11+
authorization = request.headers.get("Authorization", request.cookies.get("Authorization"))
12+
if authorization:
13+
request._headers = Headers({**request.headers, "Authorization": authorization})
14+
return await super(cls, self).__call__(request)
15+
16+
cls.__call__ = __call__
17+
return cls(*args, **kwargs)
18+
19+
return _use_cookie
20+
21+
22+
@use_cookie
23+
class OAuth2(FastAPIOAuth2):
24+
...
25+
26+
27+
@use_cookie
28+
class OAuth2PasswordBearer(FastAPIPasswordBearer):
29+
...
30+
31+
32+
@use_cookie
33+
class OAuth2AuthorizationCodeBearer(FastAPICodeBearer):
34+
...

0 commit comments

Comments
 (0)