Maintain flask_login session in flutter

579

Have you tried with the request_loader approach? You can log in from Flutter client using a url argument and the Authorization header. Quoting from the documentation,

For example, to support login from both a url argument and from Basic Auth using the Authorization header:

@login_manager.request_loader
def load_user_from_request(request):

    # first, try to login using the api_key url arg
    api_key = request.args.get('api_key')
    if api_key:
        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return user

    # next, try to login using Basic Auth
    api_key = request.headers.get('Authorization')
    if api_key:
        api_key = api_key.replace('Basic ', '', 1)
        try:
            api_key = base64.b64decode(api_key)
        except TypeError:
            pass
        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return user

    # finally, return None if both methods did not login the user
    return None

If you don't want to use flask_login anymore, I would suggest flask_jwt_extended for your case. Note that authentication will be carried out using JWT tokens instead of sessions.

Basically, you would need to create three routes: one for creating access and refresh tokens when the user logged in, one for refreshing the expired access token with the refresh token and one for removing the tokens when the user logged out. Then you would protect your API endpoints with the @jwt_required decorators.

Please refer to the documentation for detailed implementation.

Share:
579
Michail Highkhan
Author by

Michail Highkhan

Python programmer. Shipyard worker and sailor in spare time. Love cats.

Updated on December 12, 2022

Comments

  • Michail Highkhan
    Michail Highkhan over 1 year

    Soo...I have an app with flask backend and flutter frontend. It utilizes flask_login to manage users. Problem is - I don't know how to maintain session on client side. Flutter client gets response from server, but I don't see any token, or user_id inside.

    So far, I've tried to parse responce, with no luck and I've used solution from How do I make an http request using cookies on flutter? also, without success.

    Server-side https://github.com/GreenBlackSky/COIN/blob/master/api_app/app/login_bp.py

    Client-side https://github.com/GreenBlackSky/coin_web_client/blob/master/lib/session.dart

    Maybe, using flask_login was not such a good idea after all..

  • Michail Highkhan
    Michail Highkhan about 3 years
    using request_loader requires to get api_key during registration and then sending this key as argument with each request, right? I saw this example, but, apparently, made wrong conclusions at that time)
  • Michail Highkhan
    Michail Highkhan about 3 years
    I used flask_jwt_extended at the end, becouse it gives me more fine control over the authentification process, thank you)