10.26.2016

DRF JWT Authentication

i.e., Django REST Framework with JSON Web Token Authentication. Got the solution from here: http://getblimp.github.io/django-rest-framework-jwt/ http://zqpythonic.qiniucdn.com/data/20141006233346/index.html
$ pip install djangorestframework-jwt

In settings.py:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

In urls.py:
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token

urlpatterns = patterns(
    # ...
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^api-token-refresh/', refresh_jwt_token)
)

To test:
$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/
$ curl -H "Authorization: JWT " http://localhost:8000/protected-url/

No comments:

Post a Comment