0
votes

I have been trying to use the Django-REST authentication to validate the user name /password given in a desktop app.

On the server side, I have installed the following DJANGO-REST-FRAMEWORK-JWT package found here:

https://github.com/GetBlimp/django-rest-framework-jwt

I have gone through the example and when I run the following on the command line get a token as a response:

curl -X POST -d "username=luca&password=letmein123" http://localhost:8000/api-token-auth/

And I get:

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InBhbmthaiIsInVzZXJfaWQiOjIsImVtYWlsIjoiIiwiZXhwIjoxNDc5MTE5NzQ2fQ.RA085m-YSnGFheykCCxSVxI_9rW9AC9kEaOkUB5Gm0A"}

I tried something like:

import requests
resp = requests.post('http://127.0.0.1:8000/api-token-auth/', data={}, auth=('luca', 'letmein123'))

However, this always returns response code 400 with Bad request

My question is how can I do that from my desktop python app. I basically want to call the same API with the username and passord and be able to process the response and access protected APIs.

1
Did you try just passing in a dictionary as params={'username':'luca', 'password':'letmein123'} - aris
@aris Ok, I got it working by doing: resp = requests.post('http://127.0.0.1:8000/api-token-auth/', data={'username': 'luca', 'password': 'letmein123'}) - Luca
This is how I post to DRF using curl: curl -X POST --data 'foo=42&bar=17' -H 'Authorization: Token 6fae00e2d44b3da2e7fd31ff24c1d79637f47e68' http://example.com:666/rest/TempHumiditySample/ - Ross Rogers

1 Answers

0
votes

The auth parameter of requests.request is by default meant for Basic/Digest/Custom HTTP Auth, analogous to the -u, --user <user:password> parameter of curl. You could define your own custom Authentication class to achieve the desired result, but the basic way to achieve the same result as your original curl request is:

resp = requests.post(
    'http://localhost:8000/api-token-auth/',
    data={"username": "luca", "password": "letmein123"})

The data dictionary can alternatively be supplied as json by using the json parameter if you prefer (the request would be different, but also supported by Django REST framework JWT).

You can then use the token (extracted with token = resp.json()['token']) to access the restricted urls as following:

requests.post(
    'http://localhost:8000/some-personal-function/',
    json={"foo": 42},
    headers={'Authorization': 'JWT ' + token})

By the way looking at response.text might help finding the reason, which would, in the case of your 400 response, contain the following:

'{"username":["This field is required."],"password":["This field is required."]}'