M
M
Maxim Tarabrin2017-05-30 14:14:02
Django
Maxim Tarabrin, 2017-05-30 14:14:02

How to make a request to Django REST API?

How to correctly form a request to django using JWT? Let's say that I previously made a request to /api/v1/auth/login username="admin" password="123" and received a JWT in response and stored it in LocalStorage. On the next request, for example, to the address /api/v1/users/, I must form a GET request with a header, what? And with what content? Backend how should be configured:?
At the moment I have Django with Apps django:

  • 'rest_framework',
  • 'rest_framework.authtoken',

And settings:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
planc, 2017-05-30
@padr1no

www.django-rest-framework.org/api-guide/authentication
getblimp.github.io/django-rest-framework-jwt
curl -H "Authorization: JWT <your_token>" localhost:8000/protected-url
if frontend domain ! = backend domain, then the browser makes an OPTIONS request to the backend before the main request and asks - hey, I came from this domain, can I send you a request like this
, and if the server does not answer, then the browser tells the user - bummer
www.django-rest- framework.org/topics/ajax-csrf-cor...
you can either add a header with django ( https://github.com/ottoyiu/django-cors-headers/ ) or nginx :

add_header 'Access-Control-Allow-Origin' 'https://адрес фронтенда или *';
  add_header 'Access-Control-Allow-Methods' 'POST, GET, OPTIONS, PUT, DELETE';
  add_header 'Access-Control-Allow-Headers' 'Content-Type, Accept, Authorization';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question