如何在Django休息框架中验证API请求(由匿名用户)? [英] How do I authenticate API requests (by anonymous user) in Django rest framework?

查看:211
本文介绍了如何在Django休息框架中验证API请求(由匿名用户)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

API请求将由匿名用户发送。没有登录/注册功能存在。



我需要验证API请求,我尝试的一种原始方式是在每个请求中发送auth密钥。这个密钥,我被保存在角色前端作为一个常量。



必须有一个更好和更复杂的方式,请帮助!

$ b $ Django REST框架在很大程度上假设请求是基于用户进行身份验证的,但它们确实为匿名请求提供了身份验证。虽然这很大程度上违背了认证意味着验证(Django)用户是真实的假设,但是Django REST框架确实允许它发生,而只是替换 AnonymousUser 而不是。



DRF中的身份验证可以定义 request.user (经过身份验证的用户)和 request.auth (通常是使用的令牌,如果适用)请求上的属性。因此,对于您的身份验证,您将持有您创建的令牌(在模型或其他地方),而这些令牌将被验证,而不是用户凭据,您最终不会设置用户。

$来自django.contrib.auth.models导入的


$ b从rest_framework导入身份验证
从rest_framework导入异常

class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self,request):
auth = authentication.get_authorization_header(request)

如果不是auth或auth [0 ] .lower()!= b'token':
return无

如果len(auth)== 1:
msg = _('无效的标题头。提供'')
raise exception.AuthenticationFailed(msg)
elif len(auth)> 2:
msg = _('无效的标记头,凭据字符串不应包含空格')
raise exceptions.AuthenticationFailed(msg)

try:
token = Token.objects.get(token = auth [1])$ ​​b $ b除了Token.DoesNotExist:
raise exceptions.AuthenticationFailed('No such token')

return(AnonymousUser ),令牌)

此示例假设您有一个令牌存储要验证的令牌的模型。如果请求已正确验证,令牌对象将被设置为 request.auth


The API requests will be sent by anonymous users. No Login/register functionality is present.

I need to authenticate the API requests, one primitive way I tried was to send an auth key in each request. This auth key, I is saved in the Angular frontend as a constant.

There must be a better and more sophisticated way, kindly help!

解决方案

Django REST framework largely assumes that requests are authenticated based on a user, but they do provide support for authentication anonymous requests. While this largely breaks from the assumption that "authentication" means "verifying a (Django) user is genuine", Django REST framework does allow it to happen and just substitutes the AnonymousUser instead.

Authentication in DRF can define both the request.user (the authenticated user) and request.auth (generally the token used, if applicable) properties on the request. So for your authentication, you would be holding on to tokens you have created (in a model or somewhere else) and those would be validated instead of the user credentials, and you would just end up not setting the user.

from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication
from rest_framework import exceptions

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        auth = authentication.get_authorization_header(request)

        if not auth or auth[0].lower() != b'token':
            return None

        if len(auth) == 1:
            msg = _('Invalid token header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid token header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            token = Token.objects.get(token=auth[1])
        except Token.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such token')

        return (AnonymousUser(), token)

This example assumes that you have a Token model which stores the tokens that will be authenticated. The token objects will be set to request.auth if the request was authenticated properly.

这篇关于如何在Django休息框架中验证API请求(由匿名用户)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆