Django의 Google 인증 가장 간단한 방법
12792 단어 djangoallauthgoogleauthdjango
1. django 프로젝트 설정
django-admin startproject GoogleAuthentication
여기서 우리는 GoogleAuthentication이라는 django 프로젝트를 만들고 있습니다. 프로젝트 이름은 문자 그대로 무엇이든 될 수 있습니다.
2. django-allauth 패키지 설치
이제 Google 인증을 웹 애플리케이션에 추가하는 데 필요한 필수 패키지를 설치하겠습니다.
pip install django-allauth
3. settings.py에 인증 백엔드 추가
settings.py에서 AUTHENTICATION_BACKENDS 속성을 지정해야 합니다.
# settings.py
# all the below property in your settings.py file for django allauth to work
AUTHENTICATION_BACKENDS = [
# django's inbuild authentication backend
'django.contrib.auth.backends.ModelBackend',
# django's allauth authentication backend
'allauth.account.auth_backends.AuthenticationBackend',
]
4. settings.py에 필요한 앱 추가
다음 앱을 settings.py에 추가해야 합니다. django.contrib.sites가 없는 경우 INSTALLED_APPS에 추가해야 합니다.
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sites', # <-- add the sites app here
# apps needed for django all auth
'allauth',
'allauth.account',
'allauth.socialaccount',
# add the below app for google authentication to work
'allauth.socialaccount.providers.google',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
5. 기본 urls.py에 allauth URL 추가
아래 코드 스니펫을 사용하여 django의 allauth URL을 프로젝트에 포함합니다.
# main urls.py file
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')), # <- include the allauth urls here
]
6. 마이그레이션 실행
마이그레이션을 실행하려면 아래 두 명령을 사용하십시오.
python manage.py makemigrations
python manage.py migrate
7. 수퍼유저 생성
수퍼 유저를 생성하려면 다음 명령을 사용하십시오.
python manage.py createsuperuser
산출
Username (leave blank to use 'rohit'): admin
Email address: admin@admin.com
Password:
Password (again):
Superuser created successfully.
8. Google 클라이언트 ID 및 비밀번호 생성
이제 다음 링크를 방문하여 Google 개발자 대시보드를 방문하십시오. google api console
이제 검색창에서 Gmail을 검색하고 Market Place에서 Gmail API를 선택합니다.

이제 활성화 버튼을 클릭하면 Gmail API가 활성화됩니다.

이제 credentials 페이지를 방문하여 "+ CREATE CREDENTIALS "버튼을 클릭하고 "OAuth 클라이언트 ID"를 클릭하십시오.

이제 아래와 같이 응용 프로그램 유형을 웹으로 선택하십시오.

이제 애플리케이션의 이름을 원하는 대로 지정합니다. Django Google Auth로 이름을 지정하고 있지만 명심해야 할 주요 사항은 리디렉션 URL과 자바스크립트 출처입니다.
# add the following to redirect urls
http://127.0.0.1:8000/accounts/google/login/callback/
http://localhost:8000/accounts/google/login/callback/
# add the following to javascript origins
http://127.0.0.1:8000
http://localhost:8000
위의 URL을 추가한 후 만들기 버튼을 클릭합니다.

화면에 나타나는 클라이언트 ID와 시크릿을 복사합니다.
9. 클라이언트 ID 및 암호 구성
settings.py에서 다음 코드 줄을 추가합니다.
# settings.py
SITE_ID = 1
이제 django 관리 페이지에 로그인하고 example.com 사이트를 localhost로 편집합니다.

이제 소셜 애플리케이션으로 이동하여 거기에 Google 클라이언트 ID와 비밀을 추가하십시오.

위에서 클라이언트 ID와 비밀을 추가한 방법을 볼 수 있으며 선택한 사이트에 localhost를 추가하는 것을 잊지 마십시오.
방문시 : http://127.0.0.1:8000/accounts/login/
Google로 로그인할 수 있는 링크를 볼 수 있습니다. 이제 링크를 클릭하면 Google을 사용하여 로그인할 수 있습니다.
로그인 페이지

구글 인증

아래 코드 조각을 사용하여 사용자 지정 로그인 페이지를 만들 수 있습니다.
<html>
<head>
<!--Dont forget to replace with client id below-->
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
</head>
<body>
<div id="my-signin2"></div>
<script>
function onSuccess(googleUser) {
console.log('Logged in as: ' + googleUser.getBasicProfile().getName());
}
function onFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render('my-signin2', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</body>
</html>
Reference
이 문제에 관하여(Django의 Google 인증 가장 간단한 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rohit20001221/google-authentication-in-django-the-simplest-way-3982텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)