서버(Server)/장고 (Django)

dj-rest-auth 소셜 로그인(OAuth)에 대하여

Wibaek 2023. 7. 27. 23:15
728x90

dj-rest-auth는 업데이트가 중단된 django-rest-auth를 잇는 프로젝트입니다. 기능으로는 DRF를 베이스로 인증과 관련된 기능들을 간단하게 제공해 주고, django-allauth와 함께 사용하여 소셜 로그인(OAuth) 로그인과 이메일 인증등의 기능도 탑재되어 있습니다. 또한 djangorestframework-simplejwt등과 함께 사용하여 JWT기능도 지원하고 있습니다.


dj-rest-auth의 기능

REST API 인증/유저 기능

dj-rest-auth가 기본적으로 제공하는 기능은 DRF에 맞춰 REST API로 인증기능을 지원하는 것입니다. DRF는 기본적으로 따로 편리하게 제공되는 유저 인증기능은 따로 없어서 일일이 제작해야 했습니다. dj-rest-auth는 우선 기본적인 로그인 등의 기능에 대해서 URL만 설정해 주면 사용 가능하게 해 줍니다.

이메일 인증 기능

추가적으로 가입 시에 이메일 인증등을 편리하게 도와줍니다.

django-allauth와 함께 사용하여 소셜 로그인

추가적으로 django-allauth와 함께 사용하여 소셜 로그인을 편리하게 구현할 수 있습니다. 제가 중점적으로 궁금했던 것은 이 기능이고, 실제로 처음에는 이런 기능만을 위한 것인 줄 알아 이해가 느렸습니다. 그러기에 dj-rest-auth의 기본적인 목적은 REST API로 인증 기능을 제공하는 것이라는 것을 먼저 인지할 필요가 있습니다.


dj-rest-auth 사용법

그렇다면 이런 기능들을 사용하는 방법에 대해 알아보겠습니다.

기본 기능

dj-rest-auth의 공식 가이드를 보면 사용 방법이 잘 작성되어 있습니다. 가이드를 보면 우선 가장 기초 기능만 사용하려면 설치 후 다음 3개의 앱을 추가하라고 되어있습니다.

pip install dj-rest-auth
# ~~~/settings.py
INSTALLED_APPS = (
    'rest_framework',
    'rest_framework.authtoken', # 세션 인증대신 토큰 인증을 사용하기 위함
    'dj_rest_auth'
)

그리고 URL 설정도 해줍니다.

# ~~~/urls.py
urlpatterns = [
    ...
    path('dj-rest-auth/', include('dj_rest_auth.urls'))
]

저의 경우는 django-allauth까지 모든 기능을 포함하여 사용했기에 이것만으로 실험해보지는 않았지만, 해당 앱을 포함함으로써 다음과 같은 기능을 사용할 수 있을 것으로 보입니다.

  • 로그인(유저네임, 비밀번호)
  • 로그아웃
  • 비밀번호 초기화
  • 비밀번호 변경
  • 유저 정보 확인
  • 유저 정보 수정
  • 토큰 확인
  • 토큰 재발급

이러한 기능 등을 기본적으로 제공하고 있습니다.

Registration 추가

여기서 가이드를 계속 따라가면, registration기능을 사용하는 방법을 알 수 있습니다.

pip install django-allauth
# 또는
pip install 'dj-rest-auth[with_social]'

아마 둘다 가능할 것으로 보이나, 공식 가이드에는 django-allauth 설치를 위해 아래의 설치 방법을 사용하라고 서술되어 있습니다.

이후 settings.py를 수정해 줍니다.

# ~~~/settings.py
INSTALLED_APPS = (
    ...,
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'dj_rest_auth.registration',
)

SITE_ID = 1

이때 django.contrib.sites는 allauth 사용에 필요한 앱입니다. SITE_ID는 장고가 여러 사이트를 관리해야 할 때 필요한 것인데, 관련하여 많은 오류와 질문들이 있는 것을 볼 수 있었기에 다음에 좀 더 알아보고 글을 작성할 예정입니다.

위와 같이 앱 설정이 끝나면 URL할당을 통해 간단히 기능을 사용할 수 있습니다.

# auth/urls.py
urlpatterns = [
    ...
    path('dj-rest-auth/', include('dj_rest_auth.urls')),
    path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls'))
]

물론 URL 할당 경로는 임의로 지정할 수 있습니다.

# auth/urls.py
urlpatterns = [
    ...,
    path('basic/', include('dj_rest_auth.urls')),
    path('basic/registration/', include('dj_rest_auth.registration.urls'))
]

저의 경우에는 auth앱을 추가하고, 위와 같이 basic이라는 이름을 지정해 주어 소셜 로그인과 분리하여 사용했습니다.

이렇게 설정한 URL의 엔드포인트들은 아래 문서에서 확인하실 수 있습니다.

https://dj-rest-auth.readthedocs.io/en/latest/api_endpoints.html

 

또는 기능을 사용하는 것이 아닌, 실제로 작동하고 필요한 기능만을 사용하려면 다음과 같이 URL을 개별적으로 할당해 줄 수 있습니다.

# auth/urls.py
from django.urls import path
from dj_rest_auth.registration.views import RegisterView
from dj_rest_auth.views import LoginView, LogoutView, UserDetailsView

urlpatterns = [
    path("basic/register/", RegisterView.as_view(), name="rest_register"),
    path("basic/login/", LoginView.as_view(), name="rest_login"),
    path("basic/logout/", LogoutView.as_view(), name="rest_logout"),
    path("user/", UserDetailsView.as_view(), name="rest_user_details"),
]

이메일 인증 기능

추후작성

소셜 로그인 기능

dj-rest-auth의 소셜 로그인 방식

dj-rest-auth는 django-allauth와 연계하여 소셜 로그인을 처리합니다. 원래 django-allauth에서는 템플릿 태그등을 이용하여 소셜 로그인을 처리하는데, dj-rest-auth는 DRF와 연계하여 REST API로 소셜 로그인을 제공합니다.

실제 구현

# settings.py
INSTALLED_APPS = (
    ...
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.twitter',
    'allauth.socialaccount.providers.naver',
)

위와 같이 provider 앱을 추가해 주는 것으로 소셜 로그인 기능을 사용할 수 있습니다.

가이드에 따르면 확실히 지원하는 것은 Facebook, Twitter, Github, Google 로그인입니다.

지원하는 앱들은 아래와 같은 방식으로 구현이 가능합니다.

Google

# ~~~/settings.py
INSTALLED_APPS = [
    ...
    "allauth.socialaccount.providers.google",
]

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "APP": {
            "client_id": "<구글 client id>",
            "secret": "<구글 secret>",
            "key": "", # 빈 상태로 두기
        },
        "SCOPE": [
            "profile",
            "email",
        ],
        "AUTH_PARAMS": {
            "access_type": "online",
        },
        "VERIFIED_EMAIL": True,
    },
}
# auth/views.py
from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    callback_url = "http://localhost:3000/"
    client_class = OAuth2Client

레퍼런스

https://dj-rest-auth.readthedocs.io/en/latest/

 

Welcome to dj-rest-auth’s documentation! — dj-rest-auth 4.0.1 documentation

© Copyright 2020, @iMerica Revision 8a2e07de.

dj-rest-auth.readthedocs.io

https://testdriven.io/blog/django-rest-auth/

 

Django REST Framework Authentication

This tutorial looks at how to add authentication to Django REST Framework with django-allauth and dj-rest-auth.

testdriven.io

https://medium.com/chanjongs-programming-diary/django-rest-framework로-소셜-로그인-api-구현해보기-google-kakao-github-2ccc4d49a781

 

Django-Rest-Framework(DRF)로 소셜 로그인 API 구현해보기(Google, KaKao, Github)

SPA(react.js), Mobile App을 DRF(Django-Rest-Framework)와 연동하여 진행하는 프로젝트의 일환으로 소셜 로그인을 구현해 보았다.

medium.com

 

728x90