Python 如何使用 Django Rest Framework 创建登录 API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21317899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:34:28  来源:igfitidea点击:

How do I create a login API using Django Rest Framework?

pythondjangorestdjango-rest-framework

提问by JayPrime2012

I want to create a login api (or use an existing one if it is already pre-bundled) using django rest framework. However, I'm completely at a loss. Whenever I send a post request to the django rest framework "login" url, it just sends back the browsable api template page...

我想使用 django rest 框架创建一个登录 api(或者如果它已经预先捆绑,则使用现有的一个)。然而,我完全不知所措。每当我向 django rest 框架“登录”网址发送发布请求时,它只会发回可浏览的 api 模板页面...

MY CONFIGURATION

我的配置

urls.py

网址.py

url(r'^api/v1/', include('rest_framework.urls', namespace='rest_framework'))

settings.py

设置.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

WHAT I WANT

我想要的是

Request:

要求:

POST /api/v1/login  username='name' pass='pass'

Response:

回复:

200 OK "{username: 'name', 'userId': '54321'}" set-cookie: sessionid="blahblah"

采纳答案by Kevin Stone

Take a look at the api view from django-rest-framework-jwt. It's an implementation for creating auth tokens rather than cookie sessions, but your implementation will be similar. See views.pyand serializers.py. You can probably use the serializers.pyunchanged, and just adjust your views to return the right parameters and possibly set the session cookie (can't recall if that's already performed in authentication).

查看django-rest-framework-jwt的 api 视图。它是用于创建身份验证令牌而不是 cookie 会话的实现,但您的实现将是相似的。查看views.pyserializers.py。您可能可以使用未serializers.py更改的,只需调整您的视图以返回正确的参数并可能设置会话 cookie(不记得是否已经在身份验证中执行了)。

回答by TimD

If you want something like this I do the same thing however I use Token authentication.

如果你想要这样的东西,我会做同样的事情,但是我使用令牌身份验证。

Check out their token page here

在此处查看他们的令牌页面

This may not be what you want but the way I do it is (since I'm using it as a rest api endpoints for mobile clients)

这可能不是您想要的,但我这样做的方式是(因为我将它用作移动客户端的 rest api 端点)

I can do my url localhost:8000/api/users/ -H Authorization : Token A browser could then use the regular login page that you create at the provided rest framework url

我可以做我的网址localhost:8000/api/users/ -H Authorization : Token 然后浏览器可以使用您在提供的休息框架网址中创建的常规登录页面

url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')

url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')

and to get tokens for 'login-less' navigation

并获得“免登录”导航的令牌

url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')

url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')

Then if you make calls and such you can pass the authorization tokens. Of course this is just how I do it and it's probably not the most efficient way but my goal was to create a way that I can provide users with session authentication for browsers and mobile access via tokens.

然后,如果您拨打电话等,您可以传递授权令牌。当然,这就是我的做法,它可能不是最有效的方法,但我的目标是创建一种方法,我可以通过令牌为用户提供浏览器和移动访问的会话身份验证。

Then in your views.py make sure you add the authentication requirements for that view. Almost the same as session authentication section

然后在您的 views.py 中确保为该视图添加身份验证要求。与会话身份验证部分几乎相同

permission_classes = (permissions.IsAdminUser,)

permission_classes = (permissions.IsAdminUser,)

but also include

但也包括

authentication_classes = (authentication.TokenAuthentication,)

authentication_classes = (authentication.TokenAuthentication,)

I hope this helps but if not, good luck on your search.

我希望这会有所帮助,但如果没有,祝您搜索顺利。

回答by Chemical Programmer

Of course token is a good way to authenticate, but questioner is asking about session authentication.

当然令牌是一种很好的身份验证方式,但提问者正在询问会话身份验证。

Request:

要求:

POST /api/v1/login  username='username' password='password' 
  • Put csrftokenvalue at X-CSRFTokenin header
  • Even though someone using emailas username filed, usernamename parameter is required for email input (e.g. username='[email protected]')
  • csrftokenX-CSRFToken放在标题中
  • 即使有人使用email作为用户名提交,username电子邮件输入也需要名称参数(例如username='[email protected]'

Response:

回复:

302 FOUND sessionid="blahblah"
  • If you not specified nextvalue, it will automatically redirect into /accounts/profile/which can yield 404 error
  • 如果你没有指定next值,它会自动重定向到/accounts/profile/哪个会产生 404 错误

回答by mt2609

Adding our views:

添加我们的观点:

from rest_framework_jwt.views import refresh_jwt_token

urlpatterns = [
    ...
    url(r'^rest-auth/', include('rest_auth.urls')),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
    ...
    url(r'^refresh-token/', refresh_jwt_token),
]