갈루아의 반서재

Python Social Auth - Django

https://github.com/python-social-auth/social-app-django


Project documentation http://python-social-auth.readthedocs.io/en/latest/




1. Installation


1
2
3
4
5
6
7
8
9
10
# pip install social-auth-app-django
Requirement already satisfied: social-auth-app-django in /root/anaconda/envs/envalicia/lib/python3.5/site-packages
Requirement already satisfied: social-auth-core>=1.2.0 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-app-django)
Requirement already satisfied: six in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-app-django)
Requirement already satisfied: oauthlib>=1.0.3 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-core>=1.2.0->social-auth-app-django)
Requirement already satisfied: defusedxml>=0.5.0rc1 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-core>=1.2.0->social-auth-app-django)
Requirement already satisfied: PyJWT>=1.4.0 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-core>=1.2.0->social-auth-app-django)
Requirement already satisfied: python3-openid>=3.0.10 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-core>=1.2.0->social-auth-app-django)
Requirement already satisfied: requests>=2.9.1 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-core>=1.2.0->social-auth-app-django)
Requirement already satisfied: requests-oauthlib>=0.6.1 in /root/anaconda/envs/envalicia/lib/python3.5/site-packages (from social-auth-core>=1.2.0->social-auth-app-django)
cs


2. Register the application


settings.py

Django ORM 사용시
1
2
3
4
5
INSTALLED_APPS = [
    #...
    'social_django',
    #...
]
cs

MongoEngine ORM 사용시

1
2
3
4
5
6
7
INSTALLED_APPS = [
    #...
    'social_django_mongoengine',
    #...
]
 
SOCIAL_AUTH_STORAGE = 'social_django_mongoengine.models.DjangoStorage'
cs


3. Database


1
2
3
4
5
6
7
8
9
10
11
12
(envalicia) root@localhost:~/vikander#python manage.py migrate
 
Operations to perform:
  Apply all migrations: social_django
Running migrations:
  Rendering model states... DONE
  Applying social_django.0001_initial... OK
  Applying social_django.0002_add_related_name... OK
  Applying social_django.0003_alter_email_max_length... OK
  Applying social_django.0004_auto_20160423_0400... OK
  Applying social_django.0005_auto_20160727_2333... OK
  Applying social_django.0006_partial... OK
cs


4. Authentication backends


settings.py

1
2
3
4
5
6
7
8
9
10
11
AUTHENTICATION_BACKENDS = [
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.facebook.FacebookOAuth2',
    'social_core.backends.open_id.OpenIdAuth',
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.google.GoogleOAuth',
    'social_core.backends.twitter.TwitterOAuth',
    'social_core.backends.yahoo.YahooOpenId',
    'django.contrib.auth.backends.ModelBackend',
]
cs

백엔드를 정의한다. 가장 아래의 django.contrib.auth.backends.ModelBackend 을 빠뜨리면 username / password 방식으로 로그인할 수 없으므로 주의한다.


5. Add URLs entries


1
2
3
4
5
urlpatterns = [
    #...
    url('', include('social_django.urls', namespace='social')),
    #...
]
cs


6. Template Context Processors


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
TEMPLATES = [
    {
        'BACKEND''django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates/'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                #...
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
                #...
            ],
        },
    },
]
 
cs


7. Auth with Twitter


1) 어플리케이션을 생성한다(https://apps.twitter.com/app/new).



2) 부여된 키값 등을 settings.py 에 다음과 같이 등록한다.

1
2
SOCIAL_AUTH_TWITTER_KEY = '979ugihgkjkdjgkgjdg999'
SOCIAL_AUTH_TWITTER_SECRET = 'hgkgjgkgj8ug9u98999gjgkjgkgjkgjg9g999'
cs

3) 원하는 페이지에 아래와 같이 로그인 버튼을 넣는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<form action="/login/" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
</form>
 
        <div class="col-6">
            <a href="{% url 'social:begin' 'twitter' %}">
            <button class="btn btn-block btn-twitter" type="button">
                <span>Twitter</span>
            </button>
            </a>
        </div>
cs

4) 적용된 모습이다.




8. Auth with Facebook


1) Facebook 개발자 사이트(https://developers.facebook.com)에 접속한다.

2) My Apps > Add a New App > App 이름과 이메일 입력 후 생성

3) Product Setup > Facebook Login

4) 플랫폼 선택

5) Site URL 입력

6) Set Up the Facebook SDK for Javascript

로딩을 원하는 페이지의 <body> 태그 바로 다음에 아래 코드를 넣는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '121215454545',
      cookie     : true,
      xfbml      : true,
      version    : 'v2.9'
    });
    FB.AppEvents.logPageView();   
  };
 
  
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document'script''facebook-jssdk'));
 
</script>
cs

7) Login 버튼 삽입

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<form action="/login/" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
</form>
 
<div class="col-6">
    <a href="{% url 'social:begin' 'facebook' %}">
    <button class="btn btn-block btn-facebook" type="button">
        <span>Facebook</span>
    </button>
    </a>
</div>
cs

8) settings.py 파일에 App ID 와 App Secret 등 입력

1
2
3
4
5
6
7
8
9
10
11
AUTHENTICATION_BACKENDS = [
    'social_core.backends.facebook.FacebookOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]
 
SOCIAL_AUTH_URL_NAMESPACE = 'social'
 
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
 
SOCIAL_AUTH_FACEBOOK_KEY = '1900194446923010'  # App ID
SOCIAL_AUTH_FACEBOOK_SECRET = '754a791557280a91147dfac5fc2c082e'  # App Secret
cs

App Secret 는 Settings > Basic > App Secret > Show 에서 확인할 수 있다.

9) 완성된 화면이다.


10) 추가 정보 사용하기 - 이메일이 추가되었음을 알 수 있다.

settings.py

1
2
3
4
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
    'fields''id,name,email'
}
cs


public_profile 에 대한 더욱 상세한 정보는 아래 링크를 참조한다.

https://developers.facebook.com/docs/facebook-login/permissions#reference-public_profile


9. Auth with Google+


1) Google 개발자 사이트(https://console.developers.google.com/ )에 접속한다.

2) 사용자 인증 정보 > 사용자 인증 정보 만들기 > OAuth 클라이언트 ID


3) 클라이언트 ID 만들기

4) 클라이언트 ID 와 보안 비밀을 아래와 같이 입력한다.

settings.py

1
2
3
4
5
6
7
8
9
10
11
12
AUTHENTICATION_BACKENDS = [
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]
 
SOCIAL_AUTH_URL_NAMESPACE = 'social'
 
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
 
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ' 45454812151515-ghkdjg79du8ghkdjgkjdkjgk.apps.googleusercontent.com '
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ' gjldkgld9gjkldjglgj9d'
 
cs

5) 401 에러 (Invalid_client) 발생시

어플리케이션 생성에 문제가 없었다면 키 복사시 앞 뒤 공백으로 인해 위와 같은 에러가 발생하는 경우도 있으니 이 부분 반드시 체크 필요함


6) 400 에러 (redirect_uri_mismatch) 발생시


에러메시지에 표시된 대로 redirect URI 를 API 관리자의 '승인된 리디렉션 URI 에 넣어준다.


7) 적용된 모습이다.


10. GitHub


1) Github 어플리케이션 등록 사이트(https://github.com/settings/applications/new)에 접속하여 다음과 같이 새로운 어플리케이션을 생성한다. 만약 Backend not found 에러 발생시 callback URL 부분을 체크해본다.


2) 부여된 ID 와 키 값을 settings.py 에 다음과 같이 입력한다.


settings.py

1
2
3
4
5
6
AUTHENTICATION_BACKENDS = [
    'social_core.backends.github.GithubOAuth2',
]
 
SOCIAL_AUTH_GITHUB_KEY = '97gjkgkdjgkjgjkd989i80'
SOCIAL_AUTH_GITHUB_SECRET = 'dagjgodoig07979dgjod7g97d97g97g9d7dkl'
cs


3) 적용된 모습이다.