5

I am trying to setup authentication in flask-restplus application. I want to add authentication to all endpoints in the application but don't want to write decorator on each route.

I am looking for apikey based authentication. The problem is, I am unable to identify how to intercept all requests and check for authentication token in the header.

Current Code:

authorization = {
    'apikey': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'x-auth'
    }
}
api = Api(
    title='title',
    version='1.0',
    description="List of API's ",
    validate=True,
    authorizations=authorization,
    security='apikey'
)

After doing the above steps, when I open swagger I can add token using the authorize button. But once the token is passed I am unable to intercept request & verify if token is correct or not.

Currently all the examples I could find, added another decorator on each route which I don't want as it leads to poor design & duplicate code.

Currently the closest example I got is :
https://www.youtube.com/watch?v=xF30i_A6cRw&list=LLpaDwEA6bAAPZU5lz0ZRsuw&index=1

but it also uses decorator on each route.

So the problem statement is:

How to intercept all requests & check for correct token in there header without adding decorator on all routes

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49

1 Answers1

0

Very recently, I ran into a similar problem. But luckily we do have the Namespace that accepts a list of decorators, where in you can pass the custom decorator at Resource level, and it will be implemented by default to each method of that resource.

api = Namespace(
    'some Name here',
    description='some description',
    security='apiKey',
    authorizations = authorizations,
    decorators= [token_required]
)

One point to note however, I had to just specify the security with each doc in the method, as under:

@api.doc('some operation', security = 'apiKey')

The beauty with this is that one click authorization flows to each method in the resource.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Manik Jain
  • 86
  • 4