Aravind
Aravind

Reputation: 590

What is the best way to protect a flask endpoint?

I'm building a flask app where I have an end point called createUser. Now I want only admins (user type = admin) to create other users but not regular users. Using @login-required decorator will not prevent regular users from calling this end point.

One simple way this can be restricted is to check type of the user in createUser function and allow only if user is admin.

But in general what is the best way to protect flask end points and give only few users the access to end points?

Upvotes: 2

Views: 6739

Answers (1)

corvid
corvid

Reputation: 11187

generally speaking, people usually set up a decorator that will get the current_user and check their roles.

def role_required(role_name):
    def decorator(func):
        @wraps(func)
        def authorize(*args, **kwargs):
            if not current_user.has_role(role_name):
                abort(401) # not authorized
            return func(*args, **kwargs)
        return authorize
    return decorator

then in your views you can essentially do:

@app.route('/protected')
@role_required('admin')
def admin_view():
    " this view is for admins only "

Alternatively, you can use flask-bouncer

Upvotes: 7

Related Questions