Flask-auth, Principal and Flask Security [closed] Flask-auth, Principal and Flask Security [closed] flask flask

Flask-auth, Principal and Flask Security [closed]


Flask-Auth is a single solution to both authentication and permissions, but I haven't seen it used/referenced much.

Flask-Principal will do what you want, but it's pretty bare-bones; rolling your own would not be much more work.

Flask-Security rolls up Flask-Login, -Principal, and some other extensions into a more coherent whole, installing them as dependencies. Use the methods it provides rather than the ones from the individual extensions when possible. I haven't used it but it seems like it would take a lot of the manual labor out of this.

For your specific use case of just needing to add user roles, I would recommend with sticking with Flask-Principal. It works well, is maintained, and is general enough to integrate with whatever requirements you have.


In general, they are all similar but some of them have more features than other. For example, Flask-Security is very heavy with lots of extra security features like encryption extra. In fact, Flask-Security includes Flask-Principal as a subset. Flask-Principal can use Flask-Login for auth even though that is just one option. So you can see that they are all related but some are subsets or supersets of each other.

Now in your specific case, you are already using Flask-Login which is excellent. If you need to add user roles which Flask-Login does not support, I recommend you extend your User Model to add a Roles column and then overwrite the login_required decorator. If you try to use the extensions like Flask-Security etc, it might be overkill in your situation.

As example, I will extend my User class with a role field. It can have values "ANY", "ADMIN" etc. ANY means does not matter.

class User(UserMixin):    def get_role():        return rolename

I will then overwrite the login_required decorator as:

def login_required(role="ANY"):    def wrapper(fn):        @wraps(fn)        def decorated_view(*args, **kwargs):            if not current_user.is_authenticated():                 return current_app.login_manager.unauthorized()            urole = current_user.get_role()            if ( (urole != role) and (role != "ANY")):                    logout_user()                    return current_app.login_manager.unauthorized()                return fn(*args, **kwargs)           return decorated_view    return wrapper