简体   繁体   English

如何在django-rest-framework中使用TokenAuthentication for API

[英]How to use TokenAuthentication for API in django-rest-framework

I have a django project, using django-rest-framework to create api. 我有一个django项目,使用django-rest-framework来创建api。

Want to use token base authentication system so api call for (put, post, delete) will only execute for authorized user. 想要使用令牌基础认证系统,因此api调用(put,post,delete)只会为授权用户执行。

I installed 'rest_framework.authtoken' and created token for each users. 我安装了'rest_framework.authtoken'并为每个用户创建了令牌。

So, now from django.contrib.auth.backends authenticate, it returns user, with auth_token as attribute. 所以,现在从django.contrib.auth.backends身份验证,它返回用户,auth_token作为属性。 (when loged in successfully). (成功时)。

Now my question is how can I send the token with post request to my api and at api side how can I verify if token is valid and belongs to the correct user? 现在我的问题是如何将带有post请求的令牌发送到我的api和api端如何验证令牌是否有效并且属于正确的用户?

Are there any methods in app rest_framework.authtoken to validate given user and its token? app rest_framework.authtoken中是否有任何方法可以验证给定用户及其令牌? not found this very useful! 没发现这个非常有用!

Update (changes I made): Added this in my settings.py: 更新(我做的更改):在我的settings.py中添加了这个:

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

Also sending Token in my header but its still not working: 还在我的标题中发送令牌,但它仍然无法正常工作:

if new_form.is_valid:
    payload= {"createNewUser":
              { "users": request.POST["newusers"],
                "email": request.POST["newemail"]
                }
              }

    headers =  {'content-type' : 'application/json', 
                'Authorization': 'Token 6b929e47f278068fe6ac8235cda09707a3aa7ba1'}

    r = requests.post('http://localhost:8000/api/v1.0/user_list',
                      data=json.dumps(payload),
                      headers=headers, verify=False)

"how can I send the token with post request to my api" “如何将带有发布请求的令牌发送到我的api”

From the docs... 来自文档......

For clients to authenticate, the token key should be included in the Authorization HTTP header. 要使客户端进行身份验证,令牌密钥应包含在Authorization HTTP标头中。 The key should be prefixed by the string literal "Token", with whitespace separating the two strings. 密钥应以字符串文字“Token”为前缀,空格分隔两个字符串。 For example: 例如:

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

"at api side how can I verify if token is valid and belongs to the correct user?" “在api方面,我如何验证令牌是否有效并且属于正确的用户?”

You don't need to do anything, just access request.user to return the authenticated user - REST framework will deal with returning a '401 Unauthorized' response to any incorrect authentication. 您无需执行任何操作,只需访问request.user即可返回经过身份验证的用户 - REST框架将处理对任何不正确的身份验证返回“401 Unauthorized”响应。

To answer the first half of your question: 要回答你问题的前半部分:

how can I send the token with post request to my api 如何将带有发布请求的令牌发送到我的api

You can use the Python requests library. 您可以使用Python 请求库。 For the django-rest-framework TokenAuthentication, the token needs to be passed in the header and prefixed by the string Token ( see here ): 对于django-rest-framework TokenAuthentication,令牌需要在头文件中传递,并以字符串Token为前缀( 参见此处 ):

import requests
mytoken = "4652400bd6c3df8eaa360d26560ab59c81e0a164"
myurl = "http://localhost:8000/api/user_list"

# A get request (json example):
response = requests.get(myurl, headers={'Authorization': 'Token {}'.format(mytoken)})
data = response.json()

# A post request:
data = { < your post data >}
requests.post(myurl, data=data, headers={'Authorization': 'Token {}'.format(mytoken)})

I finally have the django "rest-auth" package working for token authentication. 我终于让django“rest-auth”包用于令牌认证。 If this helps, here is the client-side jQuery code that worked for me, after you successfully log in and receive the "auth_token": 如果这有帮助,那么在您成功登录并收到“auth_token”后,这是适用于我的客户端jQuery代码:

var user_url = {API URL}/rest-auth/login
var auth_headers = {
  Authorization: 'Token ' + auth_token
}
var user_ajax_obj = {
  url : user_url,
  dataType : 'json',
  headers: auth_headers,
  success : function(data) {
    console.log('authorized user returned');
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    console.log('error returned from ' + user_url);
  }
};
$.ajax(
  user_ajax_obj
);

If you are using coreapi. 如果您使用的是coreapi。 To add the Authorisation you do import coreapi auth = coreapi.auth.TokenAuthentication(scheme='Token', token=token_key) Then you can do client = coreapi.Client(auth=auth) response = client.get(my_url) 要添加授权,请执行import coreapi auth = coreapi.auth.TokenAuthentication(scheme='Token', token=token_key)然后你可以做client = coreapi.Client(auth=auth) response = client.get(my_url)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM