javascriptflaskrequestflask-loginflask-security

Is there any frontend send request code example when the backend API use @login_required from Flask-Login?


I want to implement frontend to send logout request to the flask backend below,

from flask_login import login_required, logout_user

@app.route('/auth/logout', methods=['POST'])
@login_required
def logout():
    logout_user()
    return "success", 200

I only know I should include the credential information inside the POST data.

However, even I read through the document: https://flask-login.readthedocs.io/en/latest/ and google on the internet, I didn't find a working example of frontend code that works with this kind of backend API

Is there anyone who can provide a simple frontend code example to call this backend api with credential included, thanks!


Solution

  • I got a practical code example for sending request to this API:

    fetch('https://app_hostname.com/auth/logout', {
      credentials: 'include',
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-XSRF-TOKEN': getCookieValue('XSRF-TOKEN')
      }
    });
    

    CURL command should be:

    curl -X POST -H "Content-Type: application/json, 'Accept': 'application/json', 'X-XSRF-TOKEN: xxxx'" 'https://app_hostname.com/auth/logout'
    

    Inspired by: https://flask-security-too.readthedocs.io/en/stable/patterns.html#using-a-cookie