Flask not automatically redirecting to the signin page

Viewed 961

When a session expires and the user tries to access an unauthorized page, the following message occurs (which is correct):

Redirecting...

You should be redirected automatically to target URL: /auth/sign_in. If not click the link.

The problem is that it doesn't actually redirect, I have to click on the auth/sign_in link every time - flask is not automatically redirecting me, just displaying the page. I've tested in Chrome and Firefox, same issue. I searched stack overflow a couple of times but could only find advice on fixing flask redirect, not this specific issue.

Here is my login_manager.unauthorized_handler.

@login_manager.unauthorized_handler
def unauthorized():
    flash("Please sign in to access", 'red')
    return redirect(url_for("auth.sign_in")), 401

Please let me know if there's anything else that will be helpful to show to answer the question.

1 Answers

Browsers use the 301 (moved permanently) error to redirect to other pages. This is why Flask automatically returns a 301 when redirecting. So if you return a 401 (unauthorized) error your browser won't be able to redirect. Either return 301 or just leave it blank.

return redirect(url_for("auth.sign_in")), 301

or

return redirect(url_for("auth.sign_in"))

should work.

Related