Django REST框架:使用TokenAuthentication与可浏览的API [英] Django REST Framework: using TokenAuthentication with browsable API

查看:334
本文介绍了Django REST框架:使用TokenAuthentication与可浏览的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪DRF文档以设置TokenAuthentication,并且无法使其与可浏览的API一起工作。我相信我已经在 settings.py 中添加了正确的行:

I'm following the DRF docs to setup TokenAuthentication, and can't get it working with the browsable API. I believe I've added the proper lines in settings.py:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    ),

INSTALLED_APPS = (
   ...
'rest_framework',
'rest_framework.authtoken',
   ...

以及来自文档的代码片段的现有用户生成的令牌,如果我查询 authtoken_token 表,我可以看到每个用户的令牌,所以我知道他们存在

As well as generated tokens for existing users with the code snippet from the docs. I can see tokens for each user if I query the authtoken_token table, so I know they exist.

每次我尝试登录到可浏览的API,我得到以下内容返回:

Everytime I try to log in to the browsable API, I get the following content returned:

HTTP 401 Unauthorized
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: Token

{
"detail": "Authentication credentials were not provided."
}

所以似乎正在尝试令牌a验证,但这个消息有点奇怪。当我输入错误的密码时,我会在登录表单上输入输入正确的密码信息。当我输入正确的密码,它似乎登录,但带我到上述消息的API根,并在顶部菜单上显示登录,而不是用户名。

So it appears to be attempting Token authentication, but this message is a little odd. When I enter an incorrect password, I get the 'enter a correct password' message on the login form. When I enter the correct password, it appears to login, but takes me to the API root with the above message, and displays "Log In" on the top menu, rather than the username.

这可能与我的自定义用户模型有关吗?或者可能是由于我目前正在使用不支持https的开发人员服务器(即DRF文件提到需要使用TokenAuthentication的HTTPS),尽管我不确定这是否是最佳做法或实际需要

Could this be related to my custom user model somehow? Or could it be due to the fact that I'm currently developing with the dev server, which doesn't support https- the DRF docs mention needing HTTPS with TokenAuthentication, though I wasn't sure if that was a best practice or actually required.

推荐答案

您无法使用可浏览的api与 TokenAuthentication 。您必须在您的设置中添加 SessionAuthtication http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication ):

You can't use the browsable api with TokenAuthentication. You have to add SessionAuthtication to your settings (http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication):

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

这篇关于Django REST框架:使用TokenAuthentication与可浏览的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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