Search code examples
pythondjangodjango-authenticationpythonanywhere

Why can't I authenticate from other computers on my Django site?


I've published my site with pythonanywhere, inside there is a simple login for users, I created an user and when I authenticate with my own computer it works, but when I authenticate with another machine I get this error :

Forbidden (403) - CSRF verification failed. Request aborted.

My site is published on a domain name and everything else works just fine. What can be the problem ?

Everything was set up correctly, with the correct middleware, context, csrf protections since I can login with my own computer.

Update with code :

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

login.py

def login(request):
    context = {}
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return redirect('login')
            else:
                context['error'] = 'L\'utilisateur a été désactivé'
        else:
            context['error'] = 'Mauvais nom d\'utilisateur ou mot de passe'

    return render(request, 'user.html', context)

user.html

<form method="post" action="{% url 'login' %}">
    {% csrf_token %}
    <p>Nom :<input type="text" class="form-control" name="username"></p>
    <p>Mot de passe:<input type="password" class="form-control" name="password"></p>
    <input class="submit btn btn-success pull-right" value="Se connecter" type="submit">
</form>

Solution

  • I resolved my issue by using the built in login with Django by following this tutorial :

    I didn't find the reason why my csrf checking wasn't working since there was no error on the console and the token was showing just fine using {{ csrf_token }}.