First of all, apologies for the long title but I spent quite a while trying to find the answer for this one so I thought I’d (hopefully) make it obvious to find!

I’ve been working on a new project recently that uses the Flask framework for the web application and Flask-Security for authentication and authorisation. 

When presenting content based on whether a user is authenticated or not I had noticed that if you redirect to the login page, it doesn’t always redirect back to the page with the protected content.

For example, if in my template I have this:

{%if service.spotting_data.loco_id %}
SpotterInfo*:<br />
{%if current_user.is_authenticated()%}
Loco:{{ service.spotting_data.loco_id }}
<br />
Consist:{{ service.spotting_data.consist_info }}
{%else%}
We have information on the locomotive and consist for this service, however you need to
<a href="{{ url_for('security.login') }}"> log in</a> to see it
{% endif %}
{% endif %}

Then after logging in, the user will be redirected back to the home page. 

To fix this, you need to pass the argument “next” to url_for.

When you render_template, send the request object to the template:

render_template("template.html",request=request)

then in your template you can do

{{url_for('security.login',next=request.path)}}

and you will get redirected back to the page with the protected content on login.