简体   繁体   English

如何在Django rest框架中验证API请求(由匿名用户)?

[英]How do I authenticate API requests (by anonymous user) in Django rest framework?

The API requests will be sent by anonymous users. API请求将由匿名用户发送。 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. 我需要验证API请求,我尝试过的一种原始方法是在每个请求中发送一个auth密钥。 This auth key, I is saved in the Angular frontend as a constant. 这个auth键,我作为常量保存在Angular前端。

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. Django REST框架主要假设请求是基于用户进行身份验证的,但它们确实为身份验证匿名请求提供支持。 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. 虽然这在很大程度上打破了“身份验证”意味着“验证(Django)用户是真的”的假设,但Django REST框架确实允许它发生,而只是替代AnonymousUser

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. DRF中的身份验证可以在request.user定义request.user (经过身份验证的用户)和request.auth (通常是使用的令牌,如果适用)属性。 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. 此示例假定您具有Token模型,该模型存储将要进行身份验证的令牌。 The token objects will be set to request.auth if the request was authenticated properly. 如果请求已正确验证,则令牌对象将设置为request.auth

阅读有关身份验证及其教程的其他api文档 - 它们为选项提供了可靠的介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 Django Rest 框架中的用户令牌和 API 密钥验证测试请求 - Cannot Authenticate Test Requests with Both User Token and API Key in Django Rest Framework 如何使用节流限制 Django 休息框架中每个用户的请求? - How do I limit requests per user in Django rest framework using throttling? Django rest 框架 - 如何限制对 API 端点的请求? - Django rest framework - how can i limit requests to an API endpoint? 如何在Django REST Framework中为POST请求设置权限? - How do I set permissions for POST requests in Django REST Framework? 如何在Django REST Framework API中进行用户注册 - How to do user registration in Django REST framework api 如何使用每个帐户(而非用户)具有API密钥的Django Rest框架? - How do I use an Django Rest Framework with API key per account (not user)? 如何通过 django rest 框架中的其他微服务对属于另一个数据库的用户进行身份验证? - How can I authenticate a user who belongs to another database through my other microservice in django rest framework? 无法在 Django rest 框架中对用户进行身份验证 - Can't authenticate a user in Django rest framework Django REST框架TokenAuthentication返回匿名用户 - Django REST framework TokenAuthentication returns anonymous user Django rest框架匿名用户总是经过身份验证 - Django rest framework Anonymous user is always Authenticated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM