> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/python/django-rest-framework/7.5.jwt-fang-shi-wan-cheng-yong-hu-ren-zheng.md).

# 7.5.jwt方式完成用户认证

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

安装

```bash
pip install djangorestframework-jwt
```

## Usage

于 `settings.py`中，添加`JSONWebTokenAuthentication` 到 Django REST framework中的`DEFAULT_AUTHENTICATION_CLASSES` 中

```python
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.

```python
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**.

```bash
$ 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:

```bash
$ 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.

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

## 自定义配置

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

settings.py

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

## 注意

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