Home  >  Article  >  Backend Development  >  Python server programming: using django-allauth to implement OAuth authentication

Python server programming: using django-allauth to implement OAuth authentication

王林
王林Original
2023-06-18 11:27:071382browse

In modern Internet applications, user authentication and authorization are very important factors. The OAuth (Open Authorization) protocol is one of the most commonly used authentication and authorization protocols in modern Internet development. This article will introduce how to implement OAuth authentication using Python's web framework Django and a package called django-allauth.

Django is a free and open source web application framework written in Python, which can help developers quickly build high-quality web applications. django-allauth is a Django package that provides developers with features such as social authentication, OAuth, OpenID, and email authentication.

First, we need to install Django and django-allauth. You can use the pip tool to install, the command is as follows:

pip install django
pip install django-allauth

After the installation is complete, we need to add django-allauth configuration information to the settings.py file of the Django application. Add the following at the bottom of the file:

INSTALLED_APPS = [
    # ...
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    # ...
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

SITE_ID = 1
LOGIN_REDIRECT_URL = '/'
ACCOUNT_EMAIL_VERIFICATION = 'none'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
    },
}

In the above configuration, we have enabled all auth plugins and social plugins for Django and set Google as our OAuth provider.

Add OAuth authentication to the view:
Now, we need to add the OAuth authentication function to the view. Create a view called "login" and add the following code in it:

from allauth.socialaccount.models import SocialAccount
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

@login_required
def login(request):
    social_account = SocialAccount.objects.filter(user=request.user).first()

    if social_account:
        return redirect('/')
        
    social_login = request.session.get('sociallogin')
    
    if social_login:
        if social_login.account.provider == 'google':
            social_account = SocialAccount(
                user=request.user, 
                provider=social_login.account.provider, 
                uid=social_login.account.uid, 
                extra_data=social_login.account.extra_data, 
            )
            social_account.save()
            return redirect('/')
            
    context = {
        'google_login_url': '/accounts/google/login/',
    }
    
    return render(request, 'login.html', context)

In the code of this view, first check whether the user has a social account associated with it, and if so, redirect directly to the homepage. If the user is not associated with a social account, check whether the user's session has OAuth information bound to it.

If so, we check if the OAuth information belongs to a Google account and save it as a SocialAccount object. If there is no binding, we return a dictionary containing the Google login URL and a template.

Finally, we need to add a URL to the template login.html for users to click to start OAuth authentication. A variable called "google_login_url" is used here, so we place it in the template context. The template code is as follows:

{% extends 'base.html' %}

{% block content %}
    <h1>Login</h1>
    <p>Please login with your Google account.</p>
    <a href="{{ google_login_url }}">Google Login</a>
{% endblock %}

Finally, we need to add the OAuth authentication URL pattern to the project's urls.py file. Add the following content at the bottom of the file:

from django.urls import include, path
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', login, name='login'),
]

Now our OAuth authentication functionality is complete. We can run the Django server and access the view in the browser. This will jump to Google's OAuth authentication page to request user authorization.

After the user authorizes, it will return to our Django application and redirect to the home page. In our database, there will now be a new SocialAccount record containing OAuth information about this user.

Through this article, we introduce to you how to implement OAuth authentication in Django applications. Using django-allauth is very simple and only requires a small amount of setup to perform auth. We hope this article is very helpful to people who are looking into how to use OAuth for authentication and authorization.

The above is the detailed content of Python server programming: using django-allauth to implement OAuth authentication. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn