Decorators

The following decorators are provided by Flask-Identity.

auth_required(*auth_methods)

Decorator that protects endpoints through multiple mechanisms.

Example:

@app.route('/dashboard')
@auth_required('token', 'session')
def dashboard():
    return 'Dashboard'
Parameters

auth_methods – Specified mechanisms (token, session). If not specified then all current available mechanisms will be tried.

Note that regardless of order specified - they will be tried in the following order: token, session.

The first mechanism that succeeds is used, following that, depending on configuration.

On authentication failure IdentityManager.unauthenticated() will be called.

login_required(view_function)

Ensure that the current user is logged in and authenticated before calling the actual view.

For example:

@app.route('/post')
@login_required
def post():
    pass

Note

Per W3 guidelines for CORS preflight requests, HTTP OPTIONS requests are exempt from login checks.

Parameters

view_function (function) – The view function to decorate.

roles_accepted(*role_names)

This decorator ensures that the current user is logged in, and has at least one of the specified roles (OR operation).

Example:

@route('/edit_article')
@roles_accepted('Writer', 'Editor')
def edit_article():  # User must be 'Writer' OR 'Editor'
    ...

Calls unauthenticated_view() when the user is not logged in or when user is not actived.

Calls unauthorized_view() when the user does not have the required roles.

Calls the decorated view otherwise.

roles_required(*role_names)

This decorator ensures that the current user is logged in, and has all of the specified roles (AND operation).

Example:

@route('/escape')
@roles_required('Special', 'Agent')
def escape_capture():  # User must be 'Special' AND 'Agent'
    ...

Calls unauthenticated_view() when the user is not logged in or when user is not actived.

Calls unauthorized_view() when the user does not have the required roles.

Calls the decorated view otherwise.