Django Authentication System

Shortdary·2020년 4월 29일
1

장고에서 authentication과 authorization을 제공하는 것을 "Authentication System"이라 칭한다.
authentication은 이 사람이 인증된 사람인지를 가려내는 것이고
authorization은 이 사람이 가진 권한을 명시하는 것이다.

유저객체

유저객체는 authentication system의 핵심이다. superuser던 staff던 특별한 속성이 있는 유저일 뿐이지 결국 유저는 "단 하나"의 유저 클래스이다.

유저 Authenticating

authenticate() 함수

authenticate(request=None, **credentials)

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
    # A backend authenticated the credentials
else:
    # No backend authenticated the credentials

기본으로는 username 과 password를 받아서 모든 authentication backend에 검사하여 credential이 유효하다면 유저객체를 반환한다.

authenticate 백엔드 커스터마이징

백엔드 커스터마이징은 두 개의 함수를 구현해주면 된다.

  • get_user(user_id): user_id(유저객체의 프라이머리 키)를 받아서 유저객체 또는 None을 반환한다.
  • authenticate(): request와 credentials 인자들을 받는다.
    예를 들어서 유저를 ID,비밀번호가 아닌 토큰을 사용해 authenticate를 한다면 밑과 같이 authenticate() 함수를 커스터마이징을 하면 된다.
from django.contrib.auth.backends import BaseBackend

class MyBackend(BaseBackend):
    def authenticate(self, request, token=None):
        # Check the token and return a user.
        ...

밑에 나오는 코드는 username과 password를 사용해 authenticate를 진행하는 backend 코드이다.

from django.conf import settings
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User

class SettingsBackend(BaseBackend):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'shalashala'
    """

    def authenticate(self, request, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. There's no need to set a password
                # because only the password from settings.py is checked.
                user = User(username=username)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

settings.py 에서 AUTHENTICATION_BACKENDS의 기본은 아래와 같다.

['django.contrib.auth.backends.ModelBackend']

위에서 만든 커스텀 백엔드를 여기에 추가해주면 커스텀백엔드에서 만든 authentication도 실행된다.
유의해야 할 점 하나는 백엔드를 처음것부터 순회하기 때문에 여러개의 백엔드에서 유효한 유저라도 맨 처음 걸리는 유저가 나오면 그만둔다.

기존의 유저모델 확장

유저모델 커스터마이징

Authentication in Web requests

유저로그인

세션

profile
흐엥

0개의 댓글