40 lines
1.4 KiB
Python
40 lines
1.4 KiB
Python
Here's a simple implementation of a GET /auth endpoint in FastAPI that authenticates a user:
|
|
|
|
```python
|
|
from fastapi import APIRouter, HTTPException
|
|
|
|
users = [
|
|
{"username": "demo", "password": "password"}
|
|
]
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/auth")
|
|
async def authenticate(
|
|
username: str = "demo",
|
|
password: str = "password"
|
|
):
|
|
"""Authenticate user"""
|
|
if request.method != "GET":
|
|
raise HTTPException(status_code=405, detail={
|
|
"message": "Method Not Allowed",
|
|
"method": request.method,
|
|
"_verb": "get"
|
|
})
|
|
|
|
user = next((u for u in users if u["username"] == username), None)
|
|
if not user or user["password"] != password:
|
|
raise HTTPException(status_code=400, detail="Invalid credentials")
|
|
|
|
return {
|
|
"message": "Authentication successful",
|
|
"method": "GET",
|
|
"_verb": "get",
|
|
"user": username,
|
|
"token": "dummy_jwt_token_123"
|
|
}
|
|
```
|
|
|
|
This endpoint checks if the request method is GET, and raises a 405 Method Not Allowed error if not. It then looks for a user with the provided username and password in the in-memory `users` list. If a matching user is found, it returns a successful authentication response with a dummy JWT token. Otherwise, it raises a 400 Bad Request error for invalid credentials.
|
|
|
|
The response includes the request method, a `_verb` field indicating the HTTP verb, the authenticated username, and a dummy JWT token. |