相关疑难解决方法(0)

如何在django-rest-framework中使用TokenAuthentication for API

我有一个django项目,使用django-rest-framework来创建api.

想要使用令牌基础认证系统,因此api调用(put,post,delete)只会为授权用户执行.

我安装了'rest_framework.authtoken'并为每个用户创建了令牌.

所以,现在从django.contrib.auth.backends身份验证,它返回用户,auth_token作为属性.(成功时).

现在我的问题是如何将带有post请求的令牌发送到我的api和api端如何验证令牌是否有效并且属于正确的用户?

app rest_framework.authtoken中是否有任何方法可以验证给定用户及其令牌?没发现这个非常有用!

更新(我做的更改):在我的settings.py中添加了这个:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}
Run Code Online (Sandbox Code Playgroud)

还在我的标题中发送令牌,但它仍然无法正常工作:

if new_form.is_valid:
    payload= {"createNewUser":
              { "users": request.POST["newusers"],
                "email": request.POST["newemail"]
                }
              }

    headers =  {'content-type' : 'application/json', 
                'Authorization': 'Token 6b929e47f278068fe6ac8235cda09707a3aa7ba1'}

    r = requests.post('http://localhost:8000/api/v1.0/user_list',
                      data=json.dumps(payload),
                      headers=headers, verify=False)
Run Code Online (Sandbox Code Playgroud)

python django django-authentication django-rest-framework

31
推荐指数
1
解决办法
3万
查看次数

我应该在Django Rest Framework中使用JWT或Basic Token身份验证吗?

我即将使用Django Rest Framework在我的API中实现令牌认证.但我不确定是否应该使用基本令牌内置DRF或使用JSON Web令牌(JWT)标准(使用此包djangorestframework-jwt)我发现的唯一参考是在DRF文档中:

与内置TokenAuthentication方案不同,JWT Authentication不需要使用数据库来验证令牌.

是否还有其他差异,优点或缺点需要考虑?

注意:API将从网站(使用angularjs)和移动应用程序访问

python django rest token jwt

19
推荐指数
2
解决办法
4075
查看次数

Django REST Framework如何在序列化程序中引发验证错误时指定错误代码

我有一个API端点,允许用户注册帐户.我想为重复的用户名返回HTTP 409而不是400.

这是我的序列化器:

from django.contrib.auth.models import User
from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):
    username = CharField()

    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise NameDuplicationError()
        return value


class NameDuplicationError(APIException):
    status_code = status.HTTP_409_CONFLICT
    default_detail = u'Duplicate Username'
Run Code Online (Sandbox Code Playgroud)

触发错误时,响应为:{"detail":"Duplicate Username"}.我意识到,如果我将APIException子类化,detail则使用密钥代替username.

我希望得到这个回应 {"username":"Duplicate Username"}

或者我想在引发ValidationError时指定状态代码:

def validate_username(self, value):
    if User.objects.filter(username=value).exists():
        raise serializers.ValidationError('Duplicate Username', 
                                          status_code=status.HTTP_409_CONFLICT)
    return value
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为ValidationError只返回400.

有没有其他方法可以实现这一目标?

django django-rest-framework

14
推荐指数
2
解决办法
1万
查看次数

DRF auth_token: "non_field_errors": [ "无法使用提供的凭据登录。"

为 Django 编写的两个 JWT 包都给我带来了文档不佳的问题,所以我尝试了 DRF-auth_token 包。这是我遵循的一个很好的例子,Django Rest Framework Token Authentication。理论上你应该能够去

localhost:8000/api-token-auth/

网址.py:

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework.authtoken import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include('api.urls', namespace='api')),
    url(r'^orders/', include('orders.urls', namespace='orders')),
    url(r'^api-token-auth/', views.obtain_auth_token, name='auth-token'),

]
Run Code Online (Sandbox Code Playgroud)

为用户获取令牌不起作用,所以我自己重写了它以使其工作:

@api_view(['POST'])
def customer_login(request):
    """
    Try to login a customer (food orderer)
    """
    data = request.data

    try:
        username = data['username']
        password = data['password']
    except:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        user = User.objects.get(username=username, password=password)
    except:
        return …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework django-rest-auth django-1.10

5
推荐指数
4
解决办法
2万
查看次数