Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding resources with jwt_required?

I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.

However if I add a resource that has a jwt_required decorator I get this error.

  File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator
    _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
KeyError: 'JWT_DEFAULT_REALM'

Example resource:

class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}

Initialising the app:

app = Flask(__name__)
api = Api(app)

Adding the resource:

api.add_resource(resource_class, "/myEndpoint")

The only way I can get it to work is to define the Endpoint class in the same file as the API.

I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.

like image 519
James MV Avatar asked Jul 05 '17 12:07

James MV


2 Answers

I think you forgot to initialize JWT instance. You can do it in 2 ways. First:

from flask import Flask
from flask_jwt import jwt_required, JWT
from flask_restful import Resource, Api

class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'

def authenticate(username, password):
    # you should find user in db here
    # you can see example in docs
    user = None
    if user:
        # do something
        return user

def identity(payload):
    # custom processing. the same as authenticate. see example in docs
    user_id = payload['identity']
    return None
# here what you need
jwt = JWT(app, authenticate, identity)
api = Api(app)

api.add_resource(Endpoint, '/myEndpoint')

if __name__ == '__main__':
  app.run(debug=True)
  app.run(host='0.0.0.0')

The second way is update our configuration of application. Just change:

jwt = JWT(app, authenticate, identity)

To:

app.config.update(
     JWT=JWT(app, authenticate, identity)
)

Let's open our route. You will see:

{
  "description": "Request does not contain an access token", 
  "error": "Authorization Required", 
  "status_code": 401
}

Hope it helps.

like image 193
Danila Ganchar Avatar answered Sep 23 '22 16:09

Danila Ganchar


Discovered the issue, in the resource I was importing the jwt_required:

from flask_jwt_extended import jwt_required

However I needed to import jwt_required from the class that where JWT was initalized.

like image 42
James MV Avatar answered Sep 21 '22 16:09

James MV