Starlette Basic Auth example refuses POST method? #1805
-
I am using the example straight from the https://www.starlette.io/authentication/ page as I have an application the does a basic auth POST containing a Header and a JSON Body object. I mocked up the POST it does in Postman, and tried to send this to that example app, but got 405 Method Not Allowed. I could not see where in the example it set a method (like FastAPI does), but I switched Postman to GET instead of POST and it works. I was able to collect my username/password, my custom header, and my json body object. Alas, the application I am using is coded to use POST. Is there a way to tell it to allow POST? This sample I am using: (My additions are marked with ###) from starlette.applications import Starlette
from starlette.authentication import (
AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser
)
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
import base64
import binascii
class BasicAuthBackend(AuthenticationBackend):
async def authenticate(self, conn):
if "Authorization" not in conn.headers:
return
auth = conn.headers["Authorization"]
try:
scheme, credentials = auth.split()
if scheme.lower() != 'basic':
return
decoded = base64.b64decode(credentials).decode("ascii")
except (ValueError, UnicodeDecodeError, binascii.Error) as exc:
raise AuthenticationError('Invalid basic auth credentials')
username, _, password = decoded.partition(":")
global my_user ### My Add
global my_pass #### My Add
my_user = username ### My Add
my_pass = password ### My Add
# TODO: You'd want to verify the username and password here.
return AuthCredentials(["authenticated"]), SimpleUser(username)
async def homepage(request):
if request.user.is_authenticated:
body = await request.json() ###### my add
cid = request.headers['client_id'] ###### my add
return JSONResponse({"user": my_user, "password": my_pass, "header": request.headers['client_id']}, body ) ## My Add
#return PlainTextResponse('Hello, ' + request.user.display_name)
return PlainTextResponse('Hello, you')
routes = [
Route("/", endpoint=homepage)
]
middleware = [
Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())
]
app = Starlette(routes=routes, middleware=middleware) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Just change this line: routes = [
Route("/", endpoint=homepage, methods=["POST"])
] |
Beta Was this translation helpful? Give feedback.
Just change this line: