36 lines
1.5 KiB
Python
36 lines
1.5 KiB
Python
```python
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from typing import Optional
|
|
|
|
router = APIRouter()
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")
|
|
|
|
@router.post("/logout", status_code=status.HTTP_200_OK)
|
|
async def logout(token: str = Depends(oauth2_scheme)):
|
|
"""
|
|
Logout the user by revoking the access token.
|
|
|
|
Args:
|
|
token (str): The access token to be revoked.
|
|
|
|
Returns:
|
|
dict: A JSON response indicating successful logout.
|
|
|
|
Raises:
|
|
HTTPException: If the access token is invalid or expired.
|
|
"""
|
|
# Implement token revocation logic here
|
|
# For example, you can store the revoked tokens in a database or cache
|
|
# and check if the provided token is revoked before allowing access to protected routes
|
|
|
|
return {"message": "Logout successful"}
|
|
```
|
|
|
|
This code defines a POST endpoint `/logout` that requires an access token to be provided in the `Authorization` header. The `OAuth2PasswordBearer` class is used to handle the token validation.
|
|
|
|
When a client sends a POST request to `/logout` with a valid access token, the endpoint revokes the token (by implementing the token revocation logic) and returns a JSON response with a "Logout successful" message.
|
|
|
|
If an invalid or expired token is provided, the `OAuth2PasswordBearer` will raise an `HTTPException` with a 401 Unauthorized status code.
|
|
|
|
Note: You will need to implement the actual token revocation logic based on your application's requirements and authentication mechanism. |