Reputation: 193
I have a problem with token authentication. I run my django app with django built in server.
$python manage.py runserver
My App's urls.py
from rest_framework_jwt.views import obtain_jwt_token
from .views import LectureCreateView
urlpatterns = [
...
url(r'^api/user_auth/$', obtain_jwt_token),
url(r'^api/lecture/create/$', LectureCreateView.as_view()),
]
My App's models.py
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
class LectureStartView(APIView):
permission_classes = (IsAuthenticated,)
authentication_classes = (TokenAuthentication,)
def post(self, request):
...
and settings.py
...
INSTALLED_APPS = [
...
# Rest framework
'rest_framework',
'rest_framework.authtoken',
'myApp',
]
...
REST_FRAMEWORK = {
# other settings...
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
I want auth with token. I successfully issued token.
POST '...api/user_auth/' { "username": "test", "password": "blahbalh123" }
{
"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI"
}
but I fail Auth with Token
Request:
POST ...api/lecture/create/ HTTP/1.1
Host: 127.0.0.1:8000
Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjIwMTMyMzA2Iiwib3JpZ19pYXQiOjE1MDk5NzA5NjcsInVzZXJfaWQiOjMsImVtYWlsIjoiaW50ZXJydXBpbmdAbmF2ZXIuY29tIiwiZXhwIjoxNTA5OTcxNTY3fQ.acwqAP4sBPZWYPC0GfgL3AZarNz4Opb_5P4RewZJYrI
Response:
Status: 401 Unauthorized
Allow →GET, POST, HEAD, OPTIONS
Content-Length →27
Content-Type →application/json
Date →Mon, 06 Nov 2017 12:59:17 GMT
Server →WSGIServer/0.1 Python/2.7.13
Vary →Accept
WWW-Authenticate →Token
X-Frame-Options →SAMEORIGIN
{
"detail": "Invalid token."
}
What's wrong with my code? sorry for my english skill.
Upvotes: 2
Views: 13324
Reputation: 465
I think you are mixing the Tokens from django-rest-framework and REST framework JWT.
In the DJR documentations says:
from rest_framework.authtoken import views
urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token)
]
You should replace your code with:
from rest_framework.authtoken import views
from .views import LectureCreateView
urlpatterns = [
...
url(r'^api/user_auth/$', views.obtain_auth_token),
url(r'^api/lecture/create/$', LectureCreateView.as_view()),
]
I hope it can help you.
Upvotes: 3