Django: Rest Framework authentifie l’en-tête

En utilisant l’API REST de Django , j’essaie d’authentifier ma demande.

C’est ce que j’essaye d’envoyer:

Content-Type: application/json, Authentication: token="6d82549b48a8b079f618ee9c51a6dfb59c7e2196" 

C’est ce que je récupère:

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

Quelqu’un pourrait-il me donner l’en-tête correct?

Merci

L’en-tête:

 Accept: application/json Content-Type: application/json Authorization: Token 6d82549b48a8b079f618ee9c51a6dfb59c7e2196 Connection: keep-alive Origin: chrome-extension: //rest-console-id User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17 

entrer la description de l'image ici

Settings.py

 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.permissions.IsAdminUser', ), 'PAGINATE_BY': 10 } 

view.py

 class ProfileList(generics.ListCreateAPIView): """ API endpoint that represents a list of users. """ permission_classes = (permissions.IsAuthenticated,) model = Profile serializer_class = ProfileSerializer def pre_save(self, obj): obj.owner = self.request.user 

En supposant que vous essayez d’utiliser TokenAuthentication, l’en-tête doit ressembler à ceci:

 Authorization: Token 6d82549b48a8b079f618ee9c51a6dfb59c7e2196 

Comme décrit dans la documentation .

Juste au cas où quelqu’un d’autre rencontrerait cette erreur. Cela peut également se produire si vous utilisez Django sur Apache en utilisant mod_wsgi car l’en-tête d’autorisation est supprimé par mod_wsgi. Vous devrez append les éléments suivants à votre configuration VirtualHost:

WSGIPassAuthorization On

J’avais le même problème avec mon authentification de jeton

Cela m’a corrigé le problème

settings.py

 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser' ), 'PAGINATE_BY': 10, } 

Dans mon cas, cela fonctionne:
(Django REST Framework v3)

settings.py

 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } 

views.py

 class Test(APIView): def get(self, request, format=None): return Response({'Result': 'OK'}) 

urls.py

 router.add_api_view('test', url(r'^test/', views.Test.as_view(),name='test')) 

N’oubliez pas d’envoyer les informations de jeton dans l’en-tête:

  Key: Authorization Value: Token 76efd80cd6849ad7d35e04f1cc1eea35bdc20294 

Pour générer des jetons, vous pouvez utiliser les éléments suivants (quelque part dans votre code):

 from rest_framework.authtoken.models import Token user = User.objects.get(username='') token = Token.objects.create(user=user) print(token.key) 

Pour ceux qui sont sur AWS Elastic Beanstalk et vous êtes un peu coincé avec Apache et sauf si vous avez

WSGIPassAuthorization On

Comme mentionné par @Fiver, vos en-têtes sont supprimés

Au lieu de corriger cela manuellement et de créer une nouvelle image, j’ai créé un script qui vérifie si la dernière ligne du fichier de WSGIPassAuthorization On est WSGIPassAuthorization On et si ce n’est pas le cas, nous le mettons à jour et redémarrons le serveur.

Dans mon application Django, j’ai un dossier de configuration avec mon fichier sh

configs / server / update-apache.sh

 if [[ $(tac /etc/httpd/conf/httpd.conf | egrep -m 1 .) == $(echo 'WSGIPassAuthorization On') ]]; then echo "Httpd.conf has already been updated" else echo "Updating Httpd.conf.." echo 'WSGIPassAuthorization On' >> /etc/httpd/conf/httpd.conf service httpd restart fi 

Faites-le exécuter avant que je le commette

chmod +x configs/server/update-apache.sh

Ensuite, dans mon fichier python.config, j’ajoute la commande à la fin

.ebextensions / python.config

 ... ... container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true 02_collectstatic: command: "python manage.py collectstatic --noinput" 03_change_perm: command: "chown -R wsgi:root static" 03_update_apache: command: "sh configs/server/update-apache.sh" 

Maintenant, toute nouvelle machine qui démarre aura une vérification pour voir si le serveur est mis à jour et le fait si nécessaire.