7.5.jwt方式完成用户认证

使用方式:https://jpadilla.github.io/django-rest-framework-jwt/

安装

pip install djangorestframework-jwt

Usage

settings.py中,添加JSONWebTokenAuthentication 到 Django REST framework中的DEFAULT_AUTHENTICATION_CLASSES

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

In your urls.py add the following URL route to enable obtaining a token via a POST included the user's username and password.

from rest_framework_jwt.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]

You can easily test if the endpoint is working by doing the following in your terminal, if you had a user created with the username admin and password password123.

$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/

Alternatively, you can use all the content types supported by the Django REST framework to obtain the auth token. For example:

$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/

Now in order to access protected api urls you must include the Authorization: JWT header.

$ curl -H "Authorization: JWT <your_token>" http://localhost:8000/protected-url/

自定义配置

JWT包含了大量默认配置,同时支持变更,常见的配置有token过期时间和token前缀等,如下:

settings.py

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
    'JWT_AUTH_HEADER_PREFIX': 'Token',
}

注意

jwt依赖django的认证,默认使用用户名和密码登录。若需要扩充,无需为jwt添加任何配置,直接自定义django认证即可

Last updated

Was this helpful?