django中的用户认证

本文主要介绍django的用户创建、授权,以及token等。
版本:

  • python 2.7.6
  • Django 1.8.11
  • djangorestframework 3.3.3

创建用户

使用django-admin命令创建工程时,默认创建了django的用户管理信息。
命令行下:

$ python manage.py createsuperuser --username=lanyang --email=lanyang@yhd.com

按提示输入password,完成后,查看数据库中的auth_user表,可以看到新创建的用户。

我们就可以使用这个用户登录django后台管理系统http://local.oms/api/admin/
django中的用户认证_第1张图片

Token Authentication认证

配置认证

1. 配置认证模式

settings配置文件中配置认证模式:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',

    )
}

2. 安装TokenAuthentication

settings文件中配置安装TokenAuthentication

INSTALLED_APPS = (
    ...
    'rest_framework.authtoken'
)

执行命令,使之生效:
$ python manage.py migrate

数据库中自动创建authtoken_token表。

创建token

可以用代码创建token:

from rest_framework.authtoken.models import Token

token = Token.objects.create(user=...)
print token.key

或者使用django后台管理系统为用户创建token:
django中的用户认证_第2张图片

点击”增加Token”为用户创建token:
django中的用户认证_第3张图片

创建的Token如下图:
django中的用户认证_第4张图片

token的使用

server端(Django server端):

可以从request对象中的token得到user:

request.user

例如:

from django.http import HttpResponse
from rest_framework.permissions import AllowAny, IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework.decorators import api_view, permission_classes

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def get_charm(request):
    print request.user , request.user.id
    return HttpResponse("Welcome.")

client:
发送Http请求时在header中添加token,例如:

‘Authorization’: ‘token 52cee7d4c57686ca8d6884fa4c482a99’

这个token就是authtoken_token(框架自动生成的)表中字段”key”的内容。
另外的字段”user_id”对应auth_user表中的id。
例如:

import requests

url="http://local.oms/api/ticket/charm/"
headers={'Authorization': 'token 9fb60d0f20437fbd1764df15e5c527ae184cce88'}

r = requests.get(url, headers=headers)

print r.status_code
print r.content

没有token时的结果:

401
{“detail”:”Authentication credentials were not provided.”}

提供token时的结果:

200
Welcome.

参考

用户创建、授权
http://python.usyiyi.cn/documents/django_182/topics/auth/default.html

Django官网
https://docs.djangoproject.com/en/1.11/topics/auth/default/

Django rest framework Authentication token, basic, session3中认证方式
http://www.django-rest-framework.org/api-guide/authentication/

你可能感兴趣的:(python)