1

I'm trying to implement login/registration views in Flask that support both regular login (through Flask-Security) and OAuth login (through Flask-Social).

My website uses CSRF protection, but when I implement a link to the OAuth login page (as per the Flask-Social example project) I get a CSRF error. Here is the template:

{% extends "base.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block title %}Login{% endblock %}
{% block body %}
    <h1>Login</h1>
    {% include "security/_messages.html" %}
    <form action="{{ url_for_security('login') }}" method="POST"
        name="login_user_form">
        {{ login_user_form.hidden_tag() }}
        {{ render_field_with_errors(login_user_form.email,
            class="form-control", placeholder="Your email") }}
        {{ render_field_with_errors(login_user_form.password,
            class="form-control", placeholder="Password") }}
        {{ render_field(login_user_form.remember) }}
        {{ render_field(login_user_form.next) }}
        {{ render_field(login_user_form.submit, class="btn btn-primary") }}
    </form>
    <form action="{{ url_for('social.login', provider_id='google') }}"
        name='google_login_form' method="POST">
        <input class="btn btn-primary btn-large" type="submit"
            name="login_google" value="Login with Google" >
    </form>
    {% include "security/_menu.html" %}
{% endblock %}

The problem seems to be that the second form does not have a CSRF field; what can I do about this?

Plasma
  • 2,369
  • 1
  • 29
  • 35

1 Answers1

0

You should follow the Flask-WTF docs on using templates without forms.

As per the docs, in the app

from flask_wtf.csrf import CsrfProtect

CsrfProtect(app)

and in the template

<form method="post" action="/">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>

Your second form would be

<form action="{{ url_for('social.login', provider_id='google') }}"
    name='google_login_form' method="POST">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
    <input class="btn btn-primary btn-large" type="submit"
        name="login_google" value="Login with Google" >
</form>
Eric Workman
  • 1,425
  • 12
  • 13