我使用django-allauth尝试通过AWS Cognito用户登录

首先或者一开始

之前尝试使用django-warrant和AWS Cognito进行Django登录的记录(另一网站)。但是!由于发现这个库似乎已经停止更新,所以这次尝试使用django-allauth进行登录的备忘录。

因为是OAuth2,所以似乎可以在各种服务中使用。
顺便说一下,这次的设置中貌似不会有AWS的额外费用吧?。

Django-allauth网站。

这次的环境

终端设备:Windows 10

Python 的环境

Python: 3.78.5
Django: 3.2.8(长期支持版)
Django-allauth: 0.45.0

列出所有安装的Python包。
Package            Version
------------------ ---------
asgiref            3.4.1
certifi            2021.10.8
cffi               1.15.0
charset-normalizer 2.0.7
cryptography       35.0.0
defusedxml         0.7.1
Django             3.2.8
django-allauth     0.45.0
idna               3.3
oauthlib           3.1.1
pip                21.3.1
pycparser          2.20
PyJWT              2.3.0
python3-openid     3.2.0
pytz               2021.3
requests           2.26.0
requests-oauthlib  1.3.0
setuptools         47.1.0
sqlparse           0.4.2
urllib3            1.26.7

前提 (qian ti)

以下是已安装和设置好的Python环境和AWS Cognito:已创建。

1. AWS Cognito设置

首先,需要在AWS Cognito中进行配置,以便使用OAuth2。
选择要在Cognito服务中使用的用户池。

1.1 将左侧菜单中的应用整合至应用客户端

image001.png
image002.png

1.2 左侧菜单中的应用整合->应用客户端的设置

image003.png
image010.png
如果在后续工作中遇到类似下述错误,请检查回调URL。
image006.png

将左侧菜单中的应用程序整合到域名上。

image004.png

2个Django

2.1 创建项目

确认是否可以正常启动。执行以下命令后,在http://localhost:8000上确认Django界面是否已经启动。如果是的话,就表示正常。

django-admin startproject allauth_prj
cd allauth_prj
python manage.py runserver

这是对setting.py文件进行编辑。myapp将是稍后创建的应用程序名称。

INSTALLED_APPS = [
    .........
    #ADD
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    # ADD Amazon Cognito
    'allauth.socialaccount.providers.amazon_cognito',
]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ........
                # ADD
                # `allauth` needs this from django
                'django.template.context_processors.request',
            ],
        },
    },
]
AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
]
SITE_ID = 1
SOCIALACCOUNT_PROVIDERS = {
    'amazon_cognito': {
        'DOMAIN': '<<Cognito設定時にメモしたドメインURL>>',
        'APP': {
            'client_id': '<<Cognito設定時にメモしたアプリクラアントID>>',
            'secret': '<<Cognito設定時にメモしたシークレット>>',
            'key': ''
        }
    }
}
ACCOUNT_LOGOUT_ON_GET = True

"""allauth_prj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
#Add
#from django.urls import path
from django.urls import include, path

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

2.2 数据库构建反映

执行以下命令:“python manage.py migrate”。

(venv) python manage.py migrate
on manage.py migrate
Operations to perform:
  Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying account.0001_initial... OK
  Applying account.0002_email_max_length... OK
  Applying account.0003_auto_20211023_1544... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
  Applying sites.0001_initial... OK
  Applying sites.0002_alter_domain_unique... OK
  Applying socialaccount.0001_initial... OK
  Applying socialaccount.0002_token_max_lengths... OK
  Applying socialaccount.0003_extra_data_default_dict... OK
  Applying socialaccount.0004_auto_20211023_1544... OK

使用命令`python manage.py createsuperuser` 创建超级用户,并尝试使用超级用户登录。
使用命令`python manage.py runserver` 运行服务器。

python manage.py createsuperuser

自由にユーザ情報作成


python manage.py runserver
(venv) F:\DocumentMakoto\Job\Project\Django\allauth\allauth_prj>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 23, 2021 - 19:45:34
Django version 3.2.8, using settings 'allauth_prj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

从浏览器访问并尝试登录
http://localhost:8000/admin/

image007.png
image007.png

2.3 我的应用程序开发

制作并准备myapp应用程序的登录和登出画面。

python manage.py startapp myapp

我将把myapp项目添加到setting.py中。

INSTALLED_APPS = [
    .....
    # ADD
    'myapp',
]

LOGIN_REDIRECT_URL = '/myapp'
LOGOUT_REDIRECT_URL = '/myapp'


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

urlpatterns = [
    path('admin/', admin.site.urls),
    # ADD
    path('accounts/', include('allauth.urls')),
    path('myapp/', include('myapp.urls')),
]

我app中需要进行修正。

from django.contrib import admin
from django.conf.urls import url
from django.urls import include, path
from . import views

app_name='myapp'
urlpatterns = [
    url( r'^', views.index, name='index'),
]

from django.shortcuts import render
from django.http.response import HttpResponse
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required
def index(request):
    #return HttpResponse('Login Success')

    context = {}
    return render(request, 'myapp/index.html', context )

#def logout(request):
#    return HttpResponse('Bye')


登录界面

<html>
<body>
<h1>Login Success</h1>
 Hi {{ user.username }}!
<p><a href="/accounts/logout/">Log Out</a></p>
</body>
</html>

启动 python manage.py runserver

(venv) >python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 23, 2021 - 20:08:55
Django version 3.2.8, using settings 'allauth_prj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

image008.png
image010.png
image009.png

2.4 确认账户用户

image011.png

最后的想法

特别网站没有太多困扰就创建完成了。看起来与其他网站的协作也很简单呢。
因为使用了Serverless Framework创建AWS Cognito,所以还需要考虑这一点才能编写脚本。

bannerAds