pymlup
pymlup copied to clipboard
[Feature] Add token authorization to web app
Problem
User web app can public in internet. Need add authorization
Solution
Add generated token how query params or headers.
http://localhost:8009/info?token=saasfa1123123sadasd3sadasdadsasd
In application code read from query or headers. Decorator example:
def _check_auth_token(func):
@wraps(func)
async def wrap(self, *args, request: FastAPIRequest, **kwargs):
token = request.query_params.get('token', None)
if not token:
token = request.headers.get('token', None)
if token:
token = token.replace('Bearer', '', 1).strip()
if token is None or token != VALID_TOKEN:
raise ApiRequestError('Auth token not valid.', status_code=401, type='auth_error')
return await func(self, *args, request=request, **kwargs)
return wrap
Generate auth token, if user not set custom token:
import secrets
token = secrets.token_urlsafe(32)