简体   繁体   中英

Flask-Login unauthorized endpoint redirects to wrong page

I'm using Flask-Login to manage access to routes using the @roles_required decorator. When I try to access a route to which I don't have access, I'm redirected to the application's home page at example.com and no appropriate message is flashed. If I log out, however, the login page to which I'm redirected shows all of the flashed messages that tell me that I don't have access to the route I was trying to access. If I tried to access 6 pages, 6 messages will be waiting for me.

I've updated my configuration file to include:

USER_AFTER_REGISTER_ENDPOINT    = 'confirm_email'
USER_UNCONFIRMED_EMAIL_ENDPOINT = 'confirm_email'
USER_UNAUTHENTICATED_ENDPOINT   = 'user.login'
USER_UNAUTHORIZED_ENDPOINT      = 'user.login'
USER_AFTER_CONFIRM_ENDPOINT     = 'onboarding'

All of these endpoints behave as expected EXCEPT my USER_UNAUTHORIZED_ENDPOINT .

My intention is that @role_required failures are treated the same as @login_required failures, and I believe that just fixing this redirection issue should resolve my message flashing issue.

I'm currently using Flask v1.0.2, Flask-User v0.7, Flask-Login v0.4.1.

The problem, it turned out, was that I was already logged in. When a user tried to access a route for which they lacked permissions, they WERE sent first to the login handler, but, being already logged in, they were redirected to the application home without hitting the login page and triggering the flashed messages.

To solve, I restructured the application to send logins to the application dashboard as well as unauthorized access attempts and flash both the sign in success and the role_required failures on that page.

Prior to this proper solution, I had resigned myself and simply added:

{% block home_flash %}
    {%- with messages = get_flashed_messages(with_categories=true) -%}
        {% if messages %}
            {% for category, message in messages %}
                {% if category=='error' %}
                    {% set category='danger' %}
                {% endif %}
                <div class="alert alert-{{category}}">{{ message|safe }}</div>
            {% endfor %}
        {% endif %}
    {%- endwith %}
{% endblock %}

to my home page so at least the flashed messages were getting displayed and were not backing up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM