REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
TokenAuthentication
@api_view(['GET'])
@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def example_view(request, format=None):
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
DEFAULT_AUTHENTICATION_CLASSES
를 정의TokenAuthentication
인증 방식을 사용할 것임을 명시rest_framework.authtoken
등록# settings.py
INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
# settings.py
REST_FRAMEWORK = {
# Authentication
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=...)
print(token.key)
def some_view_func(request):
token = Token.objects.create(user=...)
return Response({ 'token': token.key })
Token
문자열 함께 삽입‘ ’(공백)
으로 구분Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
dj-rest-auth
사용auth.User
를 accounts.User
로 변경 필요my_api/settings.py
수정# my_api/settings.py
INSTALLED_APPS = [
# Django Apps
'accounts',
'articles',
]
AUTH_USER_MODEL = 'accounts.User'
pip install dj-rest-auth
# settings.py
INSTALLED_APPS = (
...,
'rest_framework',
'rest_framework.authtoken',
...,
'dj_rest_auth'
)
$ python manage.py migrate
urlpatterns = [
path('dj-rest-auth/', include('dj_rest_auth.urls')),
]
공식문서 확인
Registration 기능을 사용하기 위해 추가 기능 등록 및 설치 필요
# 반드시 ''도 함께 입력
$ pip install 'dj-rest-auth[with_social]'
# my_api/settings.py
INSTALLED_APPS = (
...,
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'dj_rest_auth.registration',
)
SITE_ID = 1
# 회원가입시 토큰 발급
REST_AUTH = {
'SESSION_LOGIN': False
}
# my_api/urls.py
urlpatterns = [
path('accounts/signup/', include('dj_rest_auth.registration.urls'))
]
# allauth 추가에 대한 migrate
$ python manage.py migrate
Token
발급{
"key": "ad122b32732c21750ea4d9a0fb5e27812deff015"
}
/accounts/password/change/
기능 확인{
"headers": {"Authorization" : "Token token"},
"new_password1": "new password",
"new_password2": "new password"
}
Authorization: Token { your token }
형식에 맞춰 입력# my_api/settings.py
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
# articles/views.py
# permission Decorators
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def article_list(request):
if request.method == 'GET':
# articles = Article.objects.all()
articles = get_list_or_404(Article)
serializer = ArticleListSerializer(articles, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ArticleSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
# serializer.save(user=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
/articles/
생성 요청 확인/articles/1/
상세 조회 요청 확인DEFAULT_AUTHENTICATION_CLASSES
DEFAULT_PERMISSION_CLASSES
@authentication_classes
@permission_classes
https://github.com/mjieun0956/TIL/tree/master/Vue/14.%20DRF%20Auth%20with%20Vue/back-server