aio-libs / aio-libs/aiohttp-cors

How can I enforce CORS despite middlewares?

オープン
#481 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る
主要言語
Python
スター
220
フォーク
61
平均マージ
2分
マージ済み PR(30日)
3

説明

I implemented authentication on my app with this code:

```py
@middleware
async def auth(request, handler):
if request.headers.get("Authorization") == f"Bearer {TOKEN}":
return await handler(request)
return web.Response(status=401)
```

The problem is that OPTIONS requests don't contain authentication headers (https://stackoverflow.com/a/40723041/5133167), and the middleware doesn't return the CORS headers.

I could solve my issue by adding a condition:

```
@middleware
async def auth(request, handler):
# skip auth for OPTIONS requests
if (
request.method == "OPTIONS"
or request.headers.get("Authorization") == f"Bearer {TOKEN}"
):
return await handler(request)
return web.Response(status=401)
```

but I think it's ugly and that users shouldn't have to deal with this.

Is there a general way to enforce CORS on any middleware?

コントリビューションガイド

コントリビューションガイドを開く

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。