36👍
“how can I send the token with post request to my api”
From the docs…
For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal “Token”, with whitespace separating the two strings. For example:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
“at api side how can I verify if token is valid and belongs to the correct user?”
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.
4👍
To answer the first half of your question:
how can I send the token with post request to my api
You can use the Python requests library. For the django-rest-framework TokenAuthentication, the token needs to be passed in the header and prefixed by the string Token
(see here):
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)})
- [Django]-Iterating through two lists in Django templates
- [Django]-Django unique=True not working
- [Django]-How can one use enums as a choice field in a Django model?
1👍
I finally have the django “rest-auth” package working for token authentication.
If this helps, here is the client-side jQuery code that worked for me, after you successfully log in and receive the “auth_token”:
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
);
- [Django]-Memory efficient (constant) and speed optimized iteration over a large table in Django
- [Django]-How to test auto_now_add in django
- [Django]-Difference between setattr and object manipulation in python/django
0👍
If you are using 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)
- [Django]-Converting timezone-aware datetime to local time in Python
- [Django]-Django get list of models in application
- [Django]-How do I check for last loop iteration in Django template?