pythonhtmlflask-restfulflask-httpauth

How do I send username and password in request from frontend for auth with flask_httpauth?


I have an app that implements basic username and password authentication. I wanna be able to send username and password auth headers along with my form data when i make a request from frontend.

how can I send those username and password headers along with the request when form submit is clicked.

My verify password looks like this:

@auth.verify_password
def verify_password(username, password):
    from email_scheduler.models.api_models import User
    user = User.query.filter_by(username=username).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True

My api is this:

class TaskCreate(Resource):
    method_decorators = {'post': [auth.login_required]} #handles auth

    def post(self):
        args = task_parser.parse_args()

        from email_scheduler.models.api_models import TaskModel
        task = TaskModel(task_text=args.get('task_text'), user_id=g.user.id)
        task.save_to_db()

        return make_response(jsonify({'message': 'Task added to the database'}), 200)

It is fairly simple to do with postman, where i can just hop over to the authorization tab and put the username and password in. how do i do it if i have a frontend?


Solution

  • Unfortunately you cannot explicitly submit additional headers such as Authorization used for basic authentication with a browser issued GET or POST request. You can add do this for background requests issued from JavaScript.

    For plan browser requests, the only way to submit authentication is to force the browser to do it for you by returning a 401 status code from your endpoint. When the browser gets the 401 it will display a login dialog box where the user enters their username and password. After that the browser will add an Authorization header to any follow up requests going to that host.