2015-06-15 11 views
16

Sto cercando di far funzionare il DRF con oAuth2 (django-oauth-toolkit).Django DRF con oAuth2 che utilizza DOT (django-oauth-toolkit)

mi sono concentrato sulla http://httplambda.com/a-rest-api-with-django-and-oauthw-authentication/

Prima ho seguito tale istruzione, ma più tardi, dopo aver ottenuto errori di autenticazione, la I ha installato questa demo: https://github.com/felix-d/Django-Oauth-Toolkit-Python-Social-Auth-Integration

risultato era lo stesso: non ho potuto generare token di accesso utilizzando questo ricciolo:

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u "<client_id>:<client_secret>" http://127.0.0.1:8000/o/token/ 

ho ottenuto questo errore:

{"error": "unsupported_grant_type"} 

L'applicazione oAuth2 è stata impostata con la password grant_type. Ho cambiato grant_type a "credenziali del client" e provato questo ricciolo:

curl -X POST -d "grant_type=client_credentials" -u "<client_id>:<client_secret>" http://127.0.0.1:8000/o/token/ 

Questo ha funzionato e mi sono generato autenticazione token.

Dopo che ho cercato di ottenere un elenco di tutte le birre:

curl -H "Authorization: Bearer <auth_token>" http://127.0.0.1:8000/beers/ 

e ho ottenuto questa risposta:

{"detail":"You do not have permission to perform this action."} 

Questo è il contenuto di views.py che dovrebbe mostrare la birre:

from beers.models import Beer 
from beers.serializer import BeerSerializer 
from rest_framework import generics, permissions 

class BeerList(generics.ListCreateAPIView): 
    serializer_class = BeerSerializer 
    permission_classes = (permissions.IsAuthenticated,) 

    def get_queryset(self): 
     user = self.request.user 
     return Beer.objects.filter(owner=user) 

    def perform_create(self, serializer): 
     serializer.save(owner=self.request.user) 

Non so quale possa essere il suo problema e. Innanzitutto con "tipo di sovvenzione non selezionato" e successivamente con un'altra chiamata di ricciolo. Questo è successo anche a me quando ho fatto il tutorial di base di django-oauth-toolkit. Sto usando Django 1.8.2 e python3.4

Grazie per tutto l'aiuto!

mio settings.py assomiglia a questo

import os 
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 

SECRET_KEY = 'hd#[email protected]+^*%i+klb)o0by!bh&[email protected]' 

DEBUG = True 

TEMPLATE_DEBUG = True 

ALLOWED_HOSTS = [] 

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth', 
) 

INSTALLED_APPS = (
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 

    'oauth2_provider', 
    'rest_framework', 
    'beers', 
) 

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.clickjacking.XFrameOptionsMiddleware', 
) 

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', 
) 
ROOT_URLCONF = 'beerstash.urls' 

WSGI_APPLICATION = 'beerstash.wsgi.application' 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.sqlite3', 
     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    } 
} 

LANGUAGE_CODE = 'en-us' 

TIME_ZONE = 'UTC' 

USE_I18N = True 

USE_L10N = True 

USE_TZ = True 

STATIC_URL = '/static/' 

REST_FRAMEWORK = { 
    'DEFAULT_AUTHENTICATION_CLASSES': (
     'oauth2_provider.ext.rest_framework.OAuth2Authentication', 
    ) 
} 

OAUTH2_PROVIDER = { 
    # this is the list of available scopes 
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope'} 
} 
+0

cosa fa il tuo impostazioni assomigliano? hai aggiunto tutte le impostazioni per oauth da utilizzare come autenticazione API REST Framework? –

+0

@AlexT Ho aggiunto il mio file settings.py – bla0009

risposta

8

Ho provato demo lei ha citato e tutto andava bene.

$ curl -X POST -d "grant_type=password&username=superuser&assword=123qwe" -u"xLJuHBcdgJHNuahvER9pgqSf6vcrlbkhCr75hTCZ:nv9gzOj0BMf2cdxoxsnYZuRYTK5QwpKWiZc7USuJpm11DNtSE9X6Ob9KaVTKaQqeyQZh4KF3oZS4IJ7o9n4amzfqKJnoL7a2tYQiWgtYPSQpY6VKFjEazcqSacqTx9z8" http://127.0.0.1:8000/o/token/ 
{"access_token": "jlLpKwzReB6maEnjuJrk2HxE4RHbiA", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "DsDWz1LiSZ3bd7NVuLIp7Dkj6pbse1", "scope": "read write groups"} 
$ curl -H "Authorization: Bearer jlLpKwzReB6maEnjuJrk2HxE4RHbiA" http://127.0.0.1:8000/beers/ 
[] 

Nel tuo caso, penso, hai creato un'applicazione con "Tipo di concessione autorizzazione" errato.

Usa impostazioni questa applicazione:

Name: just a name of your choice 
Client Type: confidential 
Authorization Grant Type: Resource owner password-based 

Questo https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html#step-3-register-an-application mi halped molto.

Ecco il file di database che ho creato: https://www.dropbox.com/s/pxeyphkiy141i1l/db.sqlite3.tar.gz?dl=0

si può provare da soli. Nessun codice sorgente modificato. Nome utente dell'amministratore di Django - superutente, password - 123qwe.

+0

Ciao Yevgeniy, grazie per la tua risposta - Lo proverò e tornerò da te! – bla0009

+1

L'ho provato di nuovo - con le impostazioni come hai detto e funzionava! Grazie per la segnalazione! – bla0009

2

Quando si utilizzano le "credenziali client" non viene impostato l'utente sul token di accesso generato, questa è la radice dell'errore you do not have permission che si sta verificando.

Quando si utilizza il tipo di sovvenzione client credentials, è necessario impostare il gestore delle autorizzazioni di Rest Framework per esaminare i token come client credentials non imposta l'utente sul token generato. Django OAuth Toolkit fornisce autorizzazioni personalizzate per questo scopo:

https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/permissions.html

O se la vostra intera API è soggetto allo stesso tipo di autorizzazioni si può solo impostare il gestore l'autorizzazione a livello globale nel file settings.py, ad esempio:

REST_FRAMEWORK = { 
    'DEFAULT_AUTHENTICATION_CLASSES': (
     'oauth2_provider.ext.rest_framework.OAuth2Authentication', 
    ), 

    'DEFAULT_PERMISSION_CLASSES': (
     'oauth2_provider.ext.rest_framework.TokenHasReadWriteScope', 
    ) 
} 

Ciò presuppone naturalmente che si concedono le autorizzazioni read write al momento.

Maggiori informazioni sugli ambiti qui:

https://django-oauth-toolkit.readthedocs.org/en/latest/settings.html

Problemi correlati