[英]how can I securely perform Rest requests without authentication?
This is more a process logic question than a specific language-framework one. 与特定的语言框架相比,这更是一个过程逻辑问题。
I am developing a mobile app and want the user to be able to use it without having to login (ie try it and offer a plus to the logged users), but I don´t want other persons to make post requests from let´s say Postman or any other platform than the app without having some sort of key, so what would be the approach here? 我正在开发一个移动应用程序,希望用户无需登录即可使用它(即尝试使用它并为登录的用户提供加号),但是我不希望其他人从let's发出发帖请求在没有某种密钥的情况下说Postman或应用程序以外的任何其他平台,那么这里的方法是什么?
I am thinking on basic auth with some secret username:password for guests, or some kind of token, but as I am totally new on this I am not sure if it´s the correct approach, I´ve read the authentication and permissions Django Rest Framework tutorial but haven´t found a solution 我正在考虑使用一些秘密的用户名:访客密码或某种令牌的基本身份验证,但是由于这是我的新手,所以我不确定这是否正确,我已经阅读了Django的身份验证和权限Rest Framework教程,但尚未找到解决方案
I am learning Django myself and have gotten to the more advanced topics in the subject. 我本人正在学习Django,并已进入该主题的更高级主题。 What you could do is create a function in your permissions.py file for this. 您可以做的是在您的Permissions.py文件中创建一个函数。 like so: 像这样:
from rest_framework import permissions
class specialMobileUserPermissions(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in request.SAFE_METHODS:
return True
if request.user.id == whatever your mobile users id is:
return false
return obj.id == request.user.id # if the user is a subscribed user and they are logged in return true
return false # because we need a way out if none of the above works
So when dealing with permissions classes the permissions.SAFE_PERMISSIONS is a list of permissions that are non-destructive. 因此,在处理权限类时,permissions.SAFE_PERMISSIONS是非破坏性的权限列表。 So the first if statement asks are you a GET, HEAD, or other non data altering method. 因此,第一个if语句询问您是GET,HEAD还是其他非数据更改方法。 If so return true. 如果是这样,则返回true。
The second if statement checks the user id of the user that is making the request. 第二条if语句检查发出请求的用户的用户ID。 And if that user id is equal to the user id you set for the mobile trail user it would return false, denying permissions to whatever this class is used on. 并且,如果该用户ID等于您为移动追踪用户设置的用户ID,则它将返回false,从而拒绝使用此类的权限。
In your viewset you would need to add the permissions_classes variable like below 在您的视图集中,您将需要添加Permissions_classes变量,如下所示
from . import permissions # your permissions.py file
class FooViewSet(viewsets.ViewSet):
permission_classes = (permissions.specialMobileUserPermissions,)
Unless you need extra functionality, that should be everything you need, all the way down to the imports. 除非您需要其他功能,否则应该一直是导入所需的一切。 I hope I have helped. 我希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.