aio-libs / aio-libs/aiohttp-cors

How can I enforce CORS despite middlewares?

Aberta
#481 0 comentários 0 reações 0 responsáveis Ver no GitHub
Linguagem predominante
Python
Estrelas
220
Forks
61
Merge médio
2min
PRs com merge (30d)
3

Descrição

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?

Guia de contribuição

Abrir o guia de contribuição

Avaliação

Esta issue ainda não foi avaliada.

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.