Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flask_login and flask-JWT together in a REST API

I am new to flask, recently learned about flask_security/flask_login/flask_user.

I wish that somehow I could use flask_login along with flask-JWT, for the REST API.
Basically, I'd like to have the features like remember-me, forgot-password etc, from the flask_login
Upon searching, I found that it couldn't be done on the same flask view.

Could somebody guide me, how to do it?
Thanks.

like image 565
penka_the_cow Avatar asked Jun 14 '18 11:06

penka_the_cow


People also ask

How do you authenticate Flask API using JWT?

To do that, change the endpoint to /user and then in the headers section, add a field as x-access-token and add the JWT token in the value and click on Send. You will get the list of users as JSON. So, this is how you can perform authentication with JWT in Flask.

How do you authenticate a Flask on REST API?

To do this, you need to implement an authentication middleware. Middlewares are created in Flask by creating a decorator; a function can have multiple middlewares, and the order matters a lot. You need to add a secret key to your application; this is what you should pass to JWT.

Does Flask use JWT?

In the Flask JWT Authentication tutorial, we will build a demo application together; learn about the Flask framework, REST APIs, and Auth Token Authentication. If this is your first time implementing token authentication in Flask, don't worry!


1 Answers

flask-login provides the request_loader callback exactly for this purpose, for authenticating requests in a custom way.

In my case, I added this to my create_app function:

@login_manager.request_loader
def load_user_from_request(request):
    auth_headers = request.headers.get('Authorization', '').split()
    if len(auth_headers) != 2:
        return None
    try:
        token = auth_headers[1]
        data = jwt.decode(token, current_app.config['SECRET_KEY'])
        user = User.by_email(data['sub'])
        if user:
            return user
    except jwt.ExpiredSignatureError:
        return None
    except (jwt.InvalidTokenError, Exception) as e:
        return None
    return None

Otherwise, I followed this tutorial, so the token is created like this (in the login function):

token = jwt.encode({
'sub': user.email,
'iat':datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(minutes=30)},
current_app.config['SECRET_KEY'])

This way you can just use @login_required from flask-login instead of defining a custom decorator to protect views.

I used PyJWT instead of Flask-JWT since it seems Flask-JWT is discontinued.

like image 169
Kris Avatar answered Nov 04 '22 03:11

Kris