Skip to content

Commit

Permalink
feat: optional authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
markomirosavljev committed Oct 23, 2022
1 parent bc2f6d1 commit 53f9e78
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 4 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,18 @@ from fastapi import Depends
@app.get("/")
def hello_world(auth: CognitoToken = Depends(cognito_eu.auth_required)):
return {"message": "Hello world"}
```

### Optional authentication

If authentication should be optional, we can use ```cognito_eu.auth_optional```

Example:
```python
from fastapi_cognito import CognitoToken
from fastapi import Depends

@app.get("/")
def hello_world(auth: CognitoToken = Depends(cognito_eu.auth_optional)):
return {"message": "Hello world"}
```
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pycparser==2.20
pydantic==1.8.1
Pygments==2.8.1
pyparsing==2.4.7
python-jose==3.2.0
python-jose==3.3.0
pywin32-ctypes==0.2.0
PyYAML==5.4.1
readme-renderer==29.0
Expand Down
24 changes: 23 additions & 1 deletion src/fastapi_cognito/fastapi_cognito.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict
from typing import Dict, Optional

from cognitojwt import CognitoJWTException, decode as cognito_jwt_decode
from fastapi.exceptions import HTTPException
Expand Down Expand Up @@ -173,6 +173,28 @@ def _decode_token(self, token) -> Dict:
"your userpool region config might be incorrect."
)

def auth_optional(self, request: Request) -> Optional[CognitoToken]:
"""
Optional authentication, method will try to parse `Authorization` header
if present, else it will return None
:param request: Incoming request
:return: CognitoToken or None
"""
authorization_header = request.headers.get(
self._jwt_header_name.lower()
)

if not authorization_header:
return None

token = self._verify_header(auth_header_value=authorization_header)

try:
payload = self._decode_token(token=token)
except CognitoJWTException as error:
raise HTTPException(status_code=401, detail=str(error))
return CognitoToken(**payload)

def auth_required(self, request: Request) -> CognitoToken:
"""
Get token from request `Authorization` header use `_verify_header` to
Expand Down
4 changes: 2 additions & 2 deletions src/fastapi_cognito/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Union, Dict, List, Set, Any
from typing import Union, Dict, List, Set, Any, Optional

from pydantic import BaseModel, HttpUrl, Field

Expand All @@ -12,7 +12,7 @@ class UserpoolModel(BaseModel):
class CognitoToken(BaseModel):
origin_jti: str
cognito_id: str = Field(alias="sub")
event_id: str
event_id: Optional[str]
token_use: str
scope: str
auth_time: int
Expand Down

0 comments on commit 53f9e78

Please sign in to comment.