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后台管理系统

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:
点击Tokens

点击”增加Token”为用户创建token:
创建Token

创建的Token如下图:
Token

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/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值