Twitter OAuth with Django

I took advantage of this article and posted it. Try Twitter authentication with Django as well.

[Note] twitter OAuth with pyramid http://qiita.com/maueki/items/02f001440ce409641a50

Django standard user authentication

Before Twitter authentication, Django comes with user authentication from the beginning. First, let's look at that.

Environmental preparation

First, install django.

$ pip install django

This time I tried it with version 1.10.5. Python is 3.5.2. Next, create a Django project and create an administrator user.

$ django-admin startproject myoauth
$ cd myoauth
$ python manage.py migrate
$ python manage.py createsuperuser

Next, create an application.

$ python manage.py startapp app

Add the created app to INSTALLED_APPS in settings.py. (By the way, it may be good to change the locale setting)

setting.py


INSTALLED_APPS = (
    :
    'app.apps.AppConfig',
)

LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

The details of this area can be easily understood by looking at the tutorial of the head family. https://docs.djangoproject.com/ja/1.9/intro/tutorial01/

Login / logout page

ʻLogin to urls.py` and specify the url and view for logout. view is prepared as standard. (view is a view with MTV pattern.)

urls.py


import django.contrib.auth.views

urlpatterns = [
    :
    url(r'^login/$',
        django.contrib.auth.views.login,
        {
            'template_name': 'app/login.html',
        },
        name='login'),
    url(r'^logout/$',
        django.contrib.auth.views.logout,
        {
            'template_name': 'app/logout.html',
        },
        name='logout'),
]

login.html is prepared like this.

login.html


:
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
:

Describe the URL that will be redirected after logging in to setting.py and the URL that will be moved when you access the restricted page described later.

setting.py


LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login/'

Check login status

If you add the login_required decorator to your view, you can limit it only if you are logged in. If you are not logged in, you will be redirected to the LOGIN_URL set in setting.py.

views.py


from django.contrib.auth.decorators import login_required

@login_required
def private(request):
    ...

urls.py


urlpatterns = [
    :
    url(r'^private/$', app.views.private, name='private'),
]

You can also use the ʻuser_passes_test` decorator to add arbitrary checks to users in Lambda. The example below is limited to superuser privileges.

views.py


from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_superuser)
def private(request):
    ...

Twitter authentication

Next, try Twitter authentication.

Application registration

As a preliminary preparation, register the application from the Twitter developer page. https://apps.twitter.com

You will need these two keys.

Added library for OAuth

There seem to be various options, but this time I used social-auth-app-django. In addition to Twitter, Facebook and GitHub can be used in the same way.

$ pip install python-social-auth[django]

The version I tried this time is 1.0.0.

setting.py


INSTALLED_APPS = (
    :
    'social_django',
)

TEMPLATES = [
    {
        :
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

AUTHENTICATION_BACKENDS = [
    'social_core.backends.twitter.TwitterOAuth',
    'django.contrib.auth.backends.ModelBackend',
]

SOCIAL_AUTH_TWITTER_KEY = 'Consumer Key'
SOCIAL_AUTH_TWITTER_SECRET = 'Consumer Secret'

You can prepare a button to skip to Twitter authentication like this.

login.html


<button type="button" onclick="location.href='{% url 'social:begin' 'twitter' %}'">Twitter</button>

urls.py


urlpatterns = [
    :
    url(r'', include('social_django.urls', namespace = 'social')),
]

Since I added the application, I will migrate it at the end.

$ python manage.py migrate

You can now authenticate with Twitter. After authentication, it will be added to Django's standard user model, so you can check the login status in the same way as standard user authentication.

Recommended Posts

Twitter OAuth with Django
Qiita API Oauth with Django
Hit the Twitter API after Oauth authentication with Django
Twitter posting application made with Django
Internationalization with django
CRUD with Django
Authenticate Google with Django
Django 1.11 started with Python3.6
Upload files with Django
Development digest with Django
Output PDF with Django
Markdown output with Django
Use Gentelella with django
Getting Started with Django 1
Send email with Django
File upload with django
Use LESS with Django
Pooling mechanize with Django
Use MySQL with Django
Start today with Django
Getting Started with Django 2
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Get started with Django! ~ Tutorial ⑤ ~
Minimal website environment with django
Create an API with Django
Twitter graphing memo with Python
Get Twitter timeline with python
Use Twitter API with Python
Extract Twitter data with CSV
Do Django with CodeStar (Python3.8, Django2.1.15)
Deploy Django serverless with Lambda
Python3 + Django ~ Mac ~ with Apache
Getting Started with Python Django (1)
Create a homepage with django
Get started with Django! ~ Tutorial ④ ~
Getting Started with Python Django (4)
Web application creation with Django
Getting Started with Python Django (3)
Combine FastAPI with Django ORM
Get started with Django! ~ Tutorial ⑥ ~
Save tweet data with Django
Do AES encryption with DJango
Getting Started with Python Django (6)
Support yourself with Twitter API
Combine two images with Django
Search twitter tweets with python
Getting Started with Django with PyCharm
Real-time web with Django Channels
Double submit suppression with Django
Django REST framework with Vue.js
Successful update_with_media with twitter API
Use prefetch_related conveniently with Django
Getting Started with Python Django (5)
Login with django rest framework
Test Driven Development with Django Part 3
Steps to develop Django with VSCode
Test Driven Development with Django Part 4
Set up social login with Django
Test Driven Development with Django Part 6
Measure Django application coverage with Coverage.py
Specifying the date with the Twitter API