Flask HTTP Basicauth - How does it work?

I am trying to create a login system using Flask and HTTP Basic Auth. My question is, am I responsible for providing user information from databases, or does basicauth create and process these databases for me? If this is not the case, what can I use for this?

+4
source share
3 answers

Werkzeug can decode the Basic Authorization header for you, in a username and password. The rest is up to you to find out what you want to do with this information.

The attribute returns an object . For basic authentication headers, only and are set . request.authorizationAuthorizationusernamepassword

A simple flag fragment is available that uses this object in the decorator to protect Flask routes from some hard-coded information.

A project like this Flask-Logincan help you manage more complex inputs with Basic Authorization and bind them with the user model that you provide. This model can be stored in a database or in any other place that you so want.

And you can look at Flask-Security for a more comprehensive integrated security package that uses Flask-Login and other packages to provide basic authentication and session logins.

+12

Flask-HTTPAuth ( , ) HTTP Basic Auth. request.authorization , .

, Flask-HTTPAuth , . , .

+8

Werkzeug Authorization request.authorization, Authorization.

, 401 WWW-Authenticate. , , .

The simplest demonstration of this is the decorator, which checks request.authorizationand returns a 401 response if it is not installed or if the credentials were invalid. In practice, you should use an extension such as Flask-Login or Flask-HTTPAuth to manage this.

from functools import wraps
from flask import request

def login_required(f):
    @wraps(f)
    def wrapped_view(**kwargs):
        auth = request.authorization
        if not (auth and check_auth(auth.username, auth.password)):
            return ('Unauthorized', 401, {
                'WWW-Authenticate': 'Basic realm="Login Required"'
            })

        return f(**kwargs)

    return wrapped_view

@app.route('/secret')
@login_required
def secret():
    return f'Logged in as {request.authorization.username}.'
import requests
response = requests.get('http://127.0.0.1:5000/secret', auth=('world', 'hello'))
print(response.text)
# Logged in as world.
+1
source

Source: https://habr.com/ru/post/1535412/


All Articles