Coder Social home page Coder Social logo

realmteam / django-rest-framework-social-oauth2 Goto Github PK

View Code? Open in Web Editor NEW
1.0K 1.0K 190.0 80 KB

python-social-auth and oauth2 support for django-rest-framework

License: MIT License

Python 100.00%
django django-rest-framework oauth2 python python-social-auth

django-rest-framework-social-oauth2's People

Contributors

adamyala avatar afonsocarlos avatar alexpilot11 avatar aljazkosir avatar ashishmohite avatar bmpenuelas avatar c-bata avatar deshraj avatar dutkiewicz avatar grahamhealy20 avatar hugocore avatar islam-kamel avatar jperelli avatar knaperek avatar marcelchastain avatar mizvyt avatar oudeismetis avatar philipgarnero avatar puneetagg avatar ronlut avatar ryan-blunden avatar sukicz avatar tamayonauta avatar tejon-melero avatar trumpet2012 avatar vbabiy avatar virako avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-rest-framework-social-oauth2's Issues

After Convert Token, user is not logged

Hi,
I'm getting an extrange behaviour using facebook with DRF in my project.

1st) I make the convert token and get a good response http://www.in.usetopic.com:8000/auth/convert-token passing the correct data

and I got this answer from our server

{
access_token: "pdUOQx5MwoC7fKC79OXD3Fp36NkR8q"
token_type: "Bearer"
expires_in: 36000
refresh_token: "jdi9dVRYuJ59D5OF7vElQVdJmaDv0v"
scope: "read write groups"
}

This is correct, the user is created and everything is ok

2nd)
I go to this url to get my details

curl -H "Authorization: Bearer facebook pdUOQx5MwoC7fKC79OXD3Fp36NkR8q" http://www.in.usetopic.com:8000/api/v1/user/me

or

curl -H "Authorization: Bearer pdUOQx5MwoC7fKC79OXD3Fp36NkR8q" http://www.in.usetopic.com:8000/api/v1/user/me

I got the same answer
{"detail":"The authentication credentials are not provided."}

Facebook Invalid OAuth access token

I followed the instructions to get the project working for Facebook integration. I can sucessfully run the following command to generate my access token:

curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token

However when I then try and access my API with the token returned:

$curl -H "Authorization: Bearer facebook <backend_token>" http://localhost:8000/users/

I get the following error:

{"detail":"{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190,\"fbtrace_id\":\"HnnifuMO49M\"}}"}

Could you give me any recommendations on how to debug this? I'm happy to get you any extra information you require. I could even share the whole project source if needed, it's just a small prototype currently.

Python 3.4.3
Django==1.9.4
django-rest-framework-social-oauth2==1.0.4
djangorestframework==3.3.2
oauthlib==1.0.3
OS X 10.11.3

Potentially I set up the application wrong in Django Admin so I'm including a screenshot. The client id and secret are the values from Facebook.
screen shot 2016-03-09 at 17 23 27

Contents of settings.py:

"""
Django settings for burp project.

Generated by 'django-admin startproject' using Django 1.9.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4ae0&jjfl$f&fdlzrqavs=stcx#ntc_0)ehjr#%^!mhgqfl-$@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'corsheaders',
    'rest_framework',
    'oauth2_provider',
    'social.apps.django_app.default',
    'rest_framework_social_oauth2',
    # 'users',
    # 'topics',
    'snippets',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'PAGE_SIZE': 10,
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
}

AUTHENTICATION_BACKENDS = (
    'social.backends.facebook.FacebookOAuth2',
    'django.contrib.auth.backends.ModelBackend',
    # 'social.backends.facebook.FacebookAppOAuth2',  # Needed?
    'rest_framework_social_oauth2.backends.DjangoOAuth2',  # Needed?
)


# Start social auth settings #################################################
# TODO: delete this and test if things still work
# http://python-social-auth.readthedocs.org/en/latest/backends/facebook.html
# App ID, key? 980159652062532
SOCIAL_AUTH_FACEBOOK_KEY = '980159652062532'
SOCIAL_AUTH_FACEBOOK_SECRET = 'e6ab06ab0a1ae6b386dc072b121dfcff'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
# End social auth settings

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    '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',
]

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'burp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Settings like django.contrib.auth.context_processors.auth needed?
TEMPLATE_CONTEXT_PROCESSORS = (
    'social.apps.django_app.context_processors.backends',
    'social.apps.django_app.context_processors.login_redirect',
)

WSGI_APPLICATION = 'burp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'burp',
        'USER': 'burp',
        'HOST': '',  # localhost
        'PORT': '',
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

Thanks,
Pete

Mock a backend response

I want to test my backend. How can I mock the Facebook (or other backend) responses? I want to define a list of "valid tokens" and which are the Facebook responses for them.

How to associate uset with access token

i have login with g+ and facebook both in my app. I have this specific case which requires mandatory facebookdata, if an user is logged in from G+ i need to associate user with facebook profile using access_token not with email as i only require association and to avoid new user creation and access token again.

Send user_id in response body for 'convert-token'?

Not an issue so much as a question:

So I'm using this with Facebook, and I've got everything set up so that I'm creating new users during the social auth pipeline flow with the details from Facebook and then successfully sending back the new OAuth token with the 'convert-token' endpoint. The new user is created in my database, but the problem is that my iOS client does not know the user-id for the newly created user.

Is there a way to extend the 'convert-token' response body to also include the user's django id?

Thanks, Charlie

NotImplementedError on authentication while trying to access APIView method

Hi, I just setup django-rest-framework-social-oauth2, converted a token succefully(from facebook token to my app token) but when I'm trying to access an @apiview, it keep me showing this error:


File "/Library/Python/2.7/site-packages/social/backends/base.py", line 85, in pipeline
    out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/social/backends/base.py", line 112, in run_pipeline
    result = func(*args, **out) or {}
  File "/Library/Python/2.7/site-packages/social/pipeline/social_auth.py", line 6, in social_details
    return {'details': dict(backend.get_user_details(response), **details)}
  File "/Library/Python/2.7/site-packages/social/backends/base.py", line 165, in get_user_details
    raise NotImplementedError('Implement in subclass')
NotImplementedError: Implement in subclass

I am using this header "Authorization: Bearer MyApp <converted_token>".

Here is my view:

class VoucherList(APIView):
    permission_classes = (IsAuthenticated,)
    """
    List all user's vouchers
    """
    def get(self, request, format=None):
        vouchers = Voucher.objects.filter(owner=request.user)
        serializer = VoucherSerializer(vouchers, many=True)
        return Response(serializer.data)

And here is my current settings:

"""
Django settings for MyApp project.

Generated by 'django-admin startproject' using Django 1.9.2.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mhqk8#$_mq#+btw4vx^g4#e4(o^38$539)672z4wl7hjetij3@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'oauth2_provider',
    'social.apps.django_app.default',
    'rest_framework_social_oauth2',
    'djangobower',
    'api',
    'website',
]

PROPRIETARY_BACKEND_NAME = 'MyApp'

AUTHENTICATION_BACKENDS = (

    # Facebook OAuth2
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.facebook.FacebookOAuth2',

    # django-rest-framework-social-oauth2
    'rest_framework_social_oauth2.backends.DjangoOAuth2',

    # Django
    'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_KEY = '*****'
SOCIAL_AUTH_FACEBOOK_SECRET = '*****'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    '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',
]

ROOT_URLCONF = 'myapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'social.apps.django_app.context_processors.backends',
                'social.apps.django_app.context_processors.login_redirect',
            ],
        },
    },
]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # OAuth
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    )
}

WSGI_APPLICATION = 'myapp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

#Media files (JPEG, PNG, VIDEOS)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Django bower settings
#
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'djangobower.finders.BowerFinder',
)

BOWER_COMPONENTS_ROOT = os.path.abspath(os.path.join(BASE_DIR, 'components'))

BOWER_INSTALLED_APPS = (
    'bootstrap-material-design',
    'moment',
    'lrsjng/jquery-qrcode'
)

Twitter Convert Token Issue

Hi there,

I followed your instructions and successfully converted my facebook token to a django token via the request:
curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token

With Twitter however, I get the following error:
{"error_description": "Backend responded with HTTP403: {"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]}.", "error": "invalid_request"}
I submitted the same curl request but with twitter as the backend and my user_token as the token. I've also tried to add an additional field that uses token_secret that twitter gives me, but I get the same error too. Any thoughts as to why it would work perfectly with facebook but not with Twitter? I can't seem to figure this one out.

Thanks!
Rachel

Generate AccessToken server side

Hi,

I have created an endpoint in my application for user registration. The way I want my endpoint to work, is that a user is created (username, email and password), the user gets logged in, and a valid AccessToken is returned.

Right now, the code looks like this:

@api_view(['POST'])
def register(request):
    qp = RegisterUserSerializer(data=request.data)
    if not qp.is_valid():
        return Response(data=qp.errors, status=status.HTTP_400_BAD_REQUEST)

    username = qp['username'].value
    email = qp['email'].value
    password = qp['password'].value

    user = User.objects.create_user(username, email, password)

    auth_app_name = settings.AUTH_APPLICATION_NAME
    app = Application.objects.get(name=auth_app_name)
    token = AccessToken.objects.get_or_create(user=user, expires=now() + timedelta(days=1), application=app)

    return Response({'token': token.key}, status=status.HTTP_201_CREATED)

My issue is that I am having trouble generating the AccessToken. With the code I have now, it seems that the AccessToken is created, but that the token itself is empty. Do you have any suggestion on what might be the correct way to do this?

Invalid OAuth access token.

Hi Philip, i'm trying to test your framework in order to create social app authentication in my APIs.
After: curl -X POST -d "grant_type=convert_token&client_id=oQLj8tAr8QbbDw1uxC3AAmoSaIEL6IoO6ACSw9SS&client_secret=gDg2jwmQwRn33Oye8W5cB5nNRv9gCQCKN8fuIewilX6jIohQFS30F0zJclyLxOUPUnodP0jcgTxY6m1Rnjzvbek5fef3HCEMN9IJazkkM15MCkVzvwy36MBIEhvtNleT&backend=facebook&token=0647a7a063cd58d79038a57786fe4a57" http://localhost:8000/api/social/convert-token

I receive back the response:
{"error_description": "Backend responded with HTTP400: {"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":"Fs2FhofZ8T4"}}.", "error": "invalid_request"}

I get client_id and client_secret from admin panel. Where do I have to get the token? I tried all alternatives: client_token from dashboard and even from https://developers.facebook.com/tools/accesstoken/

This is my facebook settings code:

************* Auth Social Login **************

Facebook configuration

SOCIAL_AUTH_FACEBOOK_KEY = '926874140727083' #App ID
SOCIAL_AUTH_FACEBOOK_SECRET = '34c940f05f8d62b8f34e32f12ca4ff92' #App Secret
SOCIAL_AUTH_FACEBOOK_TOKEN = '0647a7a063cd58d79038a57786fe4a57'

Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from facebook. Email is not sent by default, to get it, you must request the email permission:

SOCIAL_AUTH_FACEBOOK_APP_NAMESPACE = 'areaoperatoriacc'
#SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

************* ***************** **************

Expired tokens

Hi @PhilipGarnero!

Question: When we use the 'convert-token' view with a local token which is expired and a third party token that is still valid, the reply is an access token with a negative expire time. Should we check for this case in the IF statement and create and return new token automatically instead of replying with the old one with a negative time and wait for a following new refresh token request?

Return example of the 'convert-token' view: {"access_token":"bf463UvVNwOehbmt2xv4vCMGVbdy3R","token_type":"Bearer","expires_in":-476339,"refresh_token":"MV1wgHB6XKqfEmPDmtoHye4eN0fJvi","scope":"read write"}

With this response, my following action in my application would be to check the "expires_in" field and check if is still positive. Otherwise, the app must send a new request to refresh this token.

AttributeError: can't set attribute when trying to use ConvertTokenView.as_view() in middleware

I'm trying to make a middleware where my final user don't need to send all the parameters unless the facebook token for ConvertTokenView:

My middleware view looks like this:

from rest_framework_social_oauth2.views import ConvertTokenView

#[.....]

    def post(self, request,  *args, **kwargs):
        #Edit request.data to call the ConvertTokenView with the needed parameters
        request.data.__setitem__("grant_type", "convert_token")
        request.data.__setitem__("backend", "facebook")
        request.data.__setitem__('client_id', Application.objects.last().client_id)
        request.data.__setitem__('client_secret', Application.objects.last().client_secret)
        request.data.__setitem__("token", request.data.get('user_access_token'))
        request.data.__setitem__("isteacher", 0)
        request._request.POST._mutable = True #Force to be mutable
        view = ConvertTokenView.as_view()
        return Response(view(request,  *args, **kwargs))

And I am getting this error:

framework_social_oauth2/views.py", line 37, in post
    request._request.POST = request._request.POST.copy()

Even when I force the request._request.POST to be mutable, it still cannot be set when I call the
view.

I know I am not using the library in a trivial way. However, I don't wan't to make my clients to store all those parameters that I can get on my app.

Is there a way I can make it work without having to change the library?

Authentication error while testing my application.

Hi,

I am using django-rest-framework-social-oauth2 along with django rest framework to develop an app. All was running well and good but when it came to testing the code, I found a bizzare error.

At the start of my testing code, I created a superuser and an application registered to him. Afterwards, I called the /auth/convert-token endpoint with my facebook access token. While it did return me an access_token, subsequent calling of other endpoints with this returned access_token always failed with the message,

"Authentication credentials were not provided"

I tried to investigate it by placing breakpoints in the function create_token of rest_framework_social_oauth2.views where I found that the AccessToken.objects.create call was not actually creating a new row in my test database (I found this by placing breakpoints after the call and investigating with external database viewer).

Note that this behavior is explicit to the testing code.

Can you please tell me what seems to be the problem here?

I am using django 1.8 with postgresql as backend and django-oauth-toolkit 0.8.1
and django-rest-framework-social-oauth2 0.0.8

Getting NotImplementedError posting to convert_token with google-oauth2 as backend

Posting to convert_token with correct tokens and incorrect tokens always gives me this error. These are some of my settings:

PROPRIETARY_BACKEND_NAME='google-oauth2'

PROPRIETARY_APPLICATION_NAME = 'Owner'

Do you have any ideas?

Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'oauth2_provider',
 'social.apps.django_app.default',
 'rest_framework',
 'rest_framework_social_oauth2',
 'viewer')
Installed Middleware:
('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',
 'django.middleware.security.SecurityMiddleware',
 'social.apps.django_app.middleware.SocialAuthExceptionMiddleware')

Traceback:
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
1.                     response = wrapped_callback(request, _callback_args, *_callback_kwargs)
   File "/app/.heroku/python/lib/python2.7/site-packages/django/views/generic/base.py" in view
2.             return self.dispatch(request, _args, *_kwargs)
   File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
3.             return bound_func(_args, *_kwargs)
   File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
4.         return view_func(_args, *_kwargs)
   File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
5.                 return func.**get**(self, type(self))(_args2, *_kwargs2)
   File "/app/.heroku/python/lib/python2.7/site-packages/braces/views/_forms.py" in dispatch
6.         return super(CsrfExemptMixin, self).dispatch(_args, *_kwargs)
   File "/app/.heroku/python/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
7.         return handler(request, _args, *_kwargs)
   File "/app/.heroku/python/lib/python2.7/site-packages/rest_framework_social_oauth2/views.py" in post
8.         url, headers, body, status = self.create_token_response(request)
   File "/app/.heroku/python/lib/python2.7/site-packages/oauth2_provider/views/mixins.py" in create_token_response
9.         return core.create_token_response(request)
   File "/app/.heroku/python/lib/python2.7/site-packages/oauth2_provider/oauth2_backends.py" in create_token_response
10.                                                                   headers)
    File "/app/.heroku/python/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py" in wrapper
11.             return f(endpoint, uri, _args, *_kwargs)
    File "/app/.heroku/python/lib/python2.7/site-packages/rest_framework_social_oauth2/oauth2_endpoints.py" in create_token_response
12.             request, self.default_token_type)
    File "/app/.heroku/python/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py" in create_token_response
13.             self.validate_token_request(request)
    File "/app/.heroku/python/lib/python2.7/site-packages/rest_framework_social_oauth2/oauth2_grants.py" in validate_token_request
14.             user = backend.do_auth(access_token=request.token)
    File "/app/.heroku/python/lib/python2.7/site-packages/social/utils.py" in wrapper
15.             return func(_args, *_kwargs)
    File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/oauth.py" in do_auth
16.         return self.strategy.authenticate(_args, *_kwargs)
    File "/app/.heroku/python/lib/python2.7/site-packages/social/strategies/django_strategy.py" in authenticate
17.         return authenticate(_args, *_kwargs)
    File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/**init**.py" in authenticate
18.             user = backend.authenticate(**credentials)
    File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py" in authenticate
19.         return self.pipeline(pipeline, _args, *_kwargs)
    File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py" in pipeline
20.         out = self.run_pipeline(pipeline, pipeline_index, _args, *_kwargs)
    File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py" in run_pipeline
21.             result = func(_args, *_out) or {}
    File "/app/.heroku/python/lib/python2.7/site-packages/social/pipeline/social_auth.py" in social_details
22.     return {'details': dict(backend.get_user_details(response), **details)}
    File "/app/.heroku/python/lib/python2.7/site-packages/social/backends/base.py" in get_user_details
23.         raise NotImplementedError('Implement in subclass')

Exception Type: NotImplementedError at /auth/convert-token
Exception Value: Implement in subclass```

unsupported_grant_type

I'm trying to authenticate an user following the instructions in the README, but when I request a token for an user, I receive:

{"error": "unsupported_grant_type"}

In my application the "Authorization grant type" field is "password" value:

In [1]: from oauth2_provider.models import Application

In [2]: a = Application.objects.get(id=1)

In [11]: a.authorization_grant_type
Out[11]: u'password'

What I'm doing wrong?

registrations with DRF

Are you planning to make registration through django-rest-framework-social-oauth2? Or it will be only authorisation?

patterns()

patterns() is deprecated in Django 1.8

Missing access_token in extra_data

The user social auths model created by python-social-auth has a json blog called extra_data. It contains info like the username and access_token from the provider.
I'm using the github backend and previously had my own endpoint to authenticate the user myself and take action when provided an access token from github. In that scenario, extra_data would contain the access_token which could be used for making API calls to github from the backend.

I have now switched to django-rest-framework-social-oauth2 and have noticed that the access_token is now null. id and login are still there and correct.

'QueryDict' object has no attribute 'iteritems'

When i run:
'curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token'

I get this error:
AttributeError at /auth/convert-token
'QueryDict' object has no attribute 'iteritems'

So i went into '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework_social_oauth2/views.py' on line 38 and changes the line to:
'for key, value in request.data.items():'
instead of:
'for key, value in request.data.iteritems():'

I don't know how to create a pull request but the reason was that python 3 uses .items() instead of .iteritems()

Send data for Python Social Auth

Hello @PhilipGarnero thank for clarify me in the other issue. I use FIELDS_STORED_IN_SESSION in Python Social Auth, can I send this data for Python Social Auth when django-rest-framework-social-oauth2 library creates a new user using Python Social Auth?

VKOAuth2 backend use wrong ID_KEY

API response does not contain field user_id, used by drfso2 by default. I made simple workaround for this issue in my settings.py

# monkeypathing social vk api
from social.backends.vk import VKOAuth2
VKOAuth2.ID_KEY = 'uid'

Error on loging with social auth

when i try to login with google , i get this error:
NoReverseMatch at /social/complete/google-oauth2/

Reverse for 'authorize' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Request Method: GET
Request URL: http://127.0.0.1:8000/social/complete/google-oauth2/?state=GjvbQRt2HA8321312lVJTAGAdgUMbV&code=4/dRm-4hiTjN4PXB7P312312321d5DEyhGgsu9tG4Ik
Django Version: 1.8.2
Exception Type: NoReverseMatch
Exception Value:

Reverse for 'authorize' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 496
Python Executable: /usr/bin/python
Python Version: 2.7.6

You can see more details here:
http://stackoverflow.com/questions/33348277/django-social-auth-error

Getting import error using django-rest-framework-social-oauth2

I have followed all the instructions mentioned in the documentation for setup but I am getting import error. Below is the stacktrace:

Traceback (most recent call last):
File "/home/vaio/git_kiti/kiti/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/default/models.py", line 8, in <module>
from social.utils import setting_name
File "/usr/local/lib/python2.7/dist-packages/social/utils.py", line 13, in <module>
from requests.packages.urllib3.poolmanager import PoolManager
ImportError: No module named packages.urllib3.poolmanager

NoReverseMatch error when loging into admin page.

Have a legitimate issue this time. When I go to the django admin site, I get this error

`Environment:

Request Method: POST
Request URL: http://localhost:8000/admin/login/?next=/admin/

Django Version: 1.8.4
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'oauth2_provider',
'users',
'social.apps.django_app.default',
'rest_framework_social_oauth2')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware')

Traceback:
File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response

  1.                 response = wrapped_callback(request, _callback_args, *_callback_kwargs)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  2.     response = view_func(request, _args, *_kwargs)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/contrib/admin/sites.py" in login
  3.     return login(request, **defaults)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
  4.         return view(request, _args, *_kwargs)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  5.                 response = view_func(request, _args, *_kwargs)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  6.     response = view_func(request, _args, *_kwargs)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/contrib/auth/views.py" in login
  7.     if form.is_valid():
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  8.     return self.is_bound and not self.errors
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/forms/forms.py" in errors
  9.         self.full_clean()
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  10.     self._clean_form()
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/forms/forms.py" in _clean_form
  11.         cleaned_data = self.clean()
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/contrib/auth/forms.py" in clean
  12.                                        password=password)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/contrib/auth/init.py" in authenticate
  13. for backend, backend_path in _get_backends(return_tuples=True):
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/contrib/auth/init.py" in _get_backends
  14.     backend = load_backend(backend_path)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/contrib/auth/init.py" in load_backend
  15. return import_string(path)()
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/utils/module_loading.py" in import_string
  16. module = import_module(module_path)
    
    File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py" in import_module
  17. **import**(name)
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/rest_framework_social_oauth2/backends.py" in
  18. class DjangoOAuth2(BaseOAuth2):
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/rest_framework_social_oauth2/backends.py" in DjangoOAuth2
  19. AUTHORIZATION_URL = reverse('authorize')
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse
  20. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, _args, *_kwargs)))
    
    File "/Users/danyalrizvi/Google_Drive/Work/gigster/blackbox/blackbox-virtualenv/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
  21.                          (lookup_view_s, args, kwargs, len(patterns), patterns))
    

Exception Type: NoReverseMatch at /admin/login/
Exception Value: Reverse for 'authorize' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []'

From my understanding the offending line is AUTHORIZATION_URL = reverse('authorize') called by class DjangoOAuth2(BaseOAuth2):. I don't understand why the rest_framework_social_oauth2 is involved at all with the default django admin.

Authentication process

Hi,

Thank you for you library. This is only a question, sorry but I am not able or allowed to add the question label. I am trying to use your library and actually I have succeeded in it. However there is something that I still do not understand. In my case I want to authenticate to a identity provider which is based on IdentityServer v3. For this reason I have checked the openID google backend and I have implemented my own, but I am still working on this.

Basically, at the moment I authenticate myself using username and password on a mobile app, then I receive the token and I send it to the convertToken API and at that point the application receives the access_token of all future request. My question is why do I need the the provider KEY and SECRET in settings.py? I have checked the convertToken API and as far as I have understood it checks the token using the user_data function which uses the user info endpoint where KEY and SECRET are not required.

Inconsistency with handling client credentials passed in request

Hi

I see that I need to pass client_id and client_secret in the request always for /auth/token/ and /auth/revoke-token/ endpoints, basically the ones which are from oauth2_provider,
But the /auth/convert-token/ and /auth/invalidate-sessions/ endpoints, views for both of which are defined in this lib itself, seem to work even when client_id and client_secret is not passed!

How do we make sure that client credentials are always passed in the request ?

application with superuser fails

README.rst says about creating application that 'user should be your superuser'. But I am getting following error for application for super user:
command:
curl -X POST -d "client_id=<client_id>&client_secret=<client_secret>&grant_type=password&username=<user_name>&password=<password>" http://localhost:8000/auth/token
error:
{"error": "invalid_grant", "error_description": "Invalid credentials given."}

Though it works fine for non superuser.

Email not added to new user after logging with Facebook

The settings.py file contains:
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

  1. I log in to Facebook with a user that doesn't exist in the User table of my Django app.
  2. I try to login server-side after having exchanged the frontend user access token with a backend token: curl -H "Authorization: Bearer facebook <backend_token>" http://localhost:8000/auth/login/facebook/

Result:
The new user has been properly created in the table but <user>.email is set to ''.

I also tried to add 'social.pipeline.social_auth.associate_by_email' to SOCIAL_AUTH_PIPELINE but the behavior didn't change.

Custom User Model

How to authenticate user from custom user model (not from django.contrib.auth)? For example i want to authenticate user from myapp.User. Thanks.

/convert-token/ is giving ValidationError on email field.

Hey folks, i am getting this error on my production server, this is though an rest framework api and this error is given just in facebook logins.

"Backend responded with HTTP500: {
"status":"error",
"code":-2,
"name":"ValidationError",
"message":"Validation error: {
  \"message\":{
    \"to\":[{\"email\":\"Sorry, this field can't be left blank.\"}]}
  }"
}."
SOCIAL_AUTH_FACEBOOK_IGNORE_DEFAULT_SCOPE = True
SOCIAL_AUTH_FACEBOOK_SCOPE = [
    'email',
]

AUTHENTICATION_BACKENDS = global_settings.AUTHENTICATION_BACKENDS + (
    # Social auth
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.facebook.FacebookOAuth2',
    'social.backends.google.GoogleOAuth2',

    # django-rest-framework-social-oauth2
    'rest_framework_social_oauth2.backends.DjangoOAuth2',

    # Django
    'django.contrib.auth.backends.ModelBackend',
)


OAUTH2_PROVIDER = {
    # this is the list of available scopes
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
        'groups': 'Access to your groups'
    },
    # Expire after a month
    'ACCESS_TOKEN_EXPIRE_SECONDS': 2592000,
}

I have a lots of configurations, some of they i dont even have sure if they really work, did someone else already pass through this error to send me an direction or how i can test it in my locahost?!

Thanks in advance.

Email not being sent when trying to convert a Facebook token

I followed the guide to configure Facebook auth, but as I tried to convert an external token using curl, I noticed only username is being sent on kwargs (and email is required in my model).

Possibly relevant stacktrace:

File ".../lib/python2.7/site-packages/social/pipeline/user.py", line 70, in create_user
    'user': strategy.create_user(**fields)
  File ".../lib/python2.7/site-packages/social/strategies/base.py", line 55, in create_user
    return self.storage.user.create_user(*args, **kwargs)
  File .../lib/python2.7/site-packages/social/storage/django_orm.py", line 60, in create_user
    return cls.user_model().objects.create_user(*args, **kwargs)
  File ".../myapp/models/user.py", line 55, in create_user
    return self._create_user(email, password, False, False, **extra_fields)
  File ".../myapp/models/user.py", line 36, in _create_user
    raise ValueError('The given email must be set')
ValueError: The given email must be set

AttributeError: 'generator' object has no attribute 'session'

Ok, this is a really weird error and it passes through a few modules.

When I try to POST to auth/convert-token, like so:

curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<token>" http://localhost:8000/auth/convert-token

I get the error:
AttributeError: 'generator' object has no attribute 'session'

I notice that ConvertTokenView calls the OAuthLibMixin for create_token_response:

(see rest_framework_social_oauth2/views.py line 34)

class ConvertTokenView(CsrfExemptMixin, OAuthLibMixin, View):
    """
    Implements an endpoint to provide access tokens
    The endpoint is used in the following flows:
    * Authorization code
    * Password
    * Client credentials
    """
    server_class = SocialTokenServer
    validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS
    oauthlib_backend_class = KeepRequestCore

    def post(self, request, *args, **kwargs):
        url, headers, body, status = self.create_token_response(request)
        response = HttpResponse(content=body, status=status)

        for k, v in headers.items():
            response[k] = v
        return response

This leads down a winding path that eventually gets to oauthlib. In the code below, the header value for 'Django-request-object' goes from being a WSGIRequest to a generator without any output, the result of the encode method here:

(see oauthlib/common.py line 380)
self.headers = CaseInsensitiveDict(encode(headers or {}))

The problem, then, is that by the time the request gets back to the SocialTokenGrant class in your library here:

(see rest_framework_social_oauth2/oauth2_grants.py line 80)

        # TODO: Find a better way to pass the django request object
        strategy = load_strategy(request=request.headers["Django-request-object"])

It's no longer a real request. And, a few calls down the chain in python-social-auth, it blows up:

(see social/strategies/django_strategy.py line 30

class DjangoStrategy(BaseStrategy):
    DEFAULT_TEMPLATE_STRATEGY = DjangoTemplateStrategy

    def __init__(self, storage, request=None, tpl=None):
        self.request = request
        self.session = request.session if request else {}
        super(DjangoStrategy, self).__init__(storage, tpl)

and produces the error:
AttributeError: 'generator' object has no attribute 'session'

Any idea how to work around this? Is there another way to get back to the Django request without having to rely on the headers coming through?

Here are the relevant parts of my requirements.txt:

Django==1.8.1
djangorestframework==3.1.2
six==1.9.0
wsgiref==0.1.2
python-social-auth==0.2.12
django-oauth-toolkit==0.9.0
django-rest-framework-social-oauth2==1.0.0

and settings.py

AUTHENTICATION_BACKENDS = (
    # Facebook OAuth2
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.facebook.FacebookOAuth2',

    # django-rest-framework-social-oauth2
    'rest_framework_social_oauth2.backends.DjangoOAuth2',

    # Django
    'django.contrib.auth.backends.ModelBackend',
)


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

SOCIAL_AUTH_FACEBOOK_KEY = env_var('SOCIAL_AUTH_FACEBOOK_KEY')
SOCIAL_AUTH_FACEBOOK_SECRET = env_var('SOCIAL_AUTH_FACEBOOK_SECRET')

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.template.context_processors.debug',
    'django.template.context_processors.i18n',
    'django.template.context_processors.media',
    'django.template.context_processors.static',
    'django.template.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'social.apps.django_app.context_processors.backends',
    'social.apps.django_app.context_processors.login_redirect',
)

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',
    'django.middleware.security.SecurityMiddleware',
    'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
)

Link between backend token and user?

After converting the third-party access token into a backend token (/convert/token/) and logging in to the app with the backend token (/login/), where is the link between the user and the token?

rest_framework.authtoken.models.Token.objects.all() returns an empty list even though 'rest_framework.authtoken' is in INSTALLED_APPS and the table has been migrated.

How to retrieve an user in my app by the facebook <user_acess_token>? [help wanted]

I read the documentation did the settings (including the facebook settings as I wish) and the last example is the following command:

curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token

When I execute this, it does the following thing on my app:

  1. Creates an user on my app with the same information I want from facebook.
  2. It returns the following information:
{"access_token":"XfMZFv7k8qBsUjIwNIM5xUcsgN2zew","token_type":"Bearer","expires_in":36000,"refresh_token":"LLyQzN7kpk7RC8Zr3oK9VeEQlE3S0r","scope":"read write"}

This seems to be the right behaviour.
However, I want to know how do I retrieve from my system this same user that was created by the last command. Should I make access_token an attribute of my user model and search for it using the returned access_token?

Facebook authorization works locally but not on production: "Authentication credentials were not provided."

Hello. I'm testing the same Django application locally and on production server and it fails to work for the production environment.

This is the pip list for both servers:

...
Django (1.7.9)
django-rest-authemail (0.1.4)
django-rest-framework-social-oauth2 (0.0.8)
djangorestframework (3.1.3)
python-openid (2.2.5)
python-social-auth (0.2.12)
...

The Django application code comes from GIT and dev/prod environment is separated by using different settings files. The difference between dev.py and production.py is currently minimal and basically just controlling the DB settings and ALLOWED_HOSTS.

The Oauth2 provider Application in both cases set to the same name and permissions. The request that I'm doing to localhost/api/convert-token and onlineserver/api/convert token is this:

curl -H "Authorization: Bearer facebook <facebook_access_token>" <url>/api/convert-token/

Doing it to a local server responses with:

{"access_token":"EAyNXqPodr6rPseg5CubASPmVBx9vg","token_type":"Bearer","expires_in":86399,"refresh_token":"7EmzTqZtHE22Zloe4dYfNaZWiamGST","scope":"read write"}

Doing it the online one:

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

The Facebook application is configured to use the domain name that is online, I thought that may be a problem, looks like it's not.

Am I missing something?

Problem with PROPRIETARY BACKEND (e.g. Django) and reverse('token')

At first thanks for your django application! It is very useful for in my projects!

I want to issue an access_token for an ordinary user (not from social network) and I try to use Django OAuth Toolkit part of your application. I create an OAuth application in my project.
Then I go to the URL:

/auth/login/Django/

(my PROPRIETARY_BACKEND_NAME is the default one) then there is a redirection to the url :

/accounts/login/?next=/auth/authorize%3Fstate...

I login with user's credentials and there is a redirection to a page to authorize the OAuth application

/auth/authorize?state=...

After the authorization I get a python error on the url (http://127.0.0.1:8000/auth/complete/MyOAuth2/?redirect_state=...)

MissingSchema at /auth/complete/Django/
Invalid URL '/auth/token': No schema supplied. Perhaps you meant http:///auth/token?

This problem as I understand is related with the code in the backends.py file
ACCESS_TOKEN_URL = reverse('token')

If I create my own backend similar to your DjangoOAuth2 and fix this argument as
ACCESS_TOKEN_URL = 'http://127.0.0.1:8000/auth/token'

I get another error :

HTTPError at /auth/complete/MyOAuth2/
405 Client Error: METHOD NOT ALLOWED

Could you, please, hint how to solve this problem ?
Cheers

API endpoints not being auto-detected by django-rest-swagger

Not sure how much of a bug this is, but I thought it was worth mentioning as there may be other implications to this issue.

I noticed that django-rest-swagger wasn't finding most of the API endpoints added by django-rest-framework-social-oauth2.

I believe the below change would fix this. I have not tested fully, but if this fix is considered relevant, let me know and I'll confirm that it works and will open a PR for it.

views.py line:21 ConvertTokenView
Currently extending django.views.generic.View. As a result, this isn't a django-rest-framework view and thus doesn't have the attributes that other tools similar to django-rest-swagger look for. Changing this to extend from rest_framework.views.APIView should fix this.

I extended ConvertTokenView in my code to make this change. It did fix it, but I ran into an issue with permissions though. That requires adding permission_classes = (AllowAny,) as this is an endpoint that should have security on it.

This fix would need to be made for every endpoint, with the exception of invalidate_sessions.

Again, let me know if this is something you want in the project and I'll go down the path of PR'ing.

Can't authenticate with converted token

I could succesfully convert my facebook app token as in:
curl -X POST -d "grant_type=convert_token&client_id=...&client_secret=...&backend=facebook&token=..." http://localhost:5000/auth/convert-token
obtaining:
{"scope":"read write","access_token":"as27yv1V5LbMCFmvWR2VJZDF4e5BjN","refresh_token":"19ME11GLXpj8FiJJy4LRhPMWloJzl9","token_type":"Bearer","expires_in":36000}

But then when I try to retrieve data I can't use the converted token to authenticate:
curl -H "Authorizaton: Bearer as27yv1V5LbMCFmvWR2VJZDF4e5BjN" http://localhost:5000/recipes/
obtaining:
{"detail":"Authentication credentials were not provided."}

What am I missing?

PD: this is my settings.py:

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'p!!xd0ir)1h^xm_fh96(^s&ie5tdxgjpn9wg%sr*h_=mkj5--$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

DEFAULT_APPS = (
    # 'django.contrib.admin',    # small fix: hvad, dal, oauth2, corsheaders... must go before django.contrib.admin
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

THIRD_PARTY_APPS = (
    'hvad',
    'dal',
    'dal_select2',
    'django.contrib.admin',     # small fix: hvad, dal, oauth2, corsheaders... must go before django.contrib.admin
    'mathfilters',
    'rest_framework',
    'oauth2_provider',
    'corsheaders',
    'social.apps.django_app.default',
    'rest_framework_social_oauth2',
)

LOCAL_APPS = (
    'homepage',
    'accounts',
    'purchases',
    'recipes',
    'stores',
    #'notifications',
)

INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    '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',
    'corsheaders.middleware.CorsMiddleware',
)

CORS_ORIGIN_ALLOW_ALL = True # TODO: only for the tests!

# Authentication
AUTHENTICATION_BACKENDS = (
    # Facebook OAuth2
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.facebook.FacebookOAuth2',

    # django-rest-framework-social-oauth2
    'rest_framework_social_oauth2.backends.DjangoOAuth2',

    # 'accounts.backends.EmailBackend',

    # Django
    'django.contrib.auth.backends.ModelBackend'
)

# Facebook configuration
SOCIAL_AUTH_FACEBOOK_KEY = '1186092684755591'
SOCIAL_AUTH_FACEBOOK_SECRET = '24b731c13267e2f86d0cb02eeae84492'
SOCIAL_AUTH_FACEBOOK_APP_NAMESPACE = 'eficook-test'

# Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from facebook. Email is not sent by default, to get it, you must request the email permission:
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

LOGIN_REDIRECT_URL = '/accounts/home'

ROOT_URLCONF = 'eficook.urls'

WSGI_APPLICATION = 'eficook.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'eficook_dev',
        'USER': 'martibosch',
        'PASSWORD': 'Scarlett1',
        'HOST': 'localhost',
        'PORT': '',
    }
}

import dj_database_url
DATABASES['default'] = dj_database_url.config(default='postgres://martibosch:Scarlett1@localhost/eficook_dev')

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'ca'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

gettext = lambda s: s
LANGUAGES = (
    ('ca', gettext('Catalan')),
    ('es', gettext('Spanish')),
)

# Model translation



# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

# Media files

MEDIA_ROOT = 'mediafiles'
MEDIA_URL = '/media/'

# Templates

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'social.apps.django_app.context_processors.backends',
                'social.apps.django_app.context_processors.login_redirect',
            ],
        },
    },
]

# TEMPLATE_DEBUG = True

# TEMPLATE_DIRS = (
#     os.path.join(BASE_DIR, 'templates'),
# )

# REST API
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )    
}

Callback function.

I want to design call back functions for my app using django-rest-framework-social-oauth2 is it possible to do so? If yes, then how? I tried finding it out in the documentation did not get anything on it.

Google Oauth2

Have you ever used this with Google's Oauth2?

I followed your example to convert a facebook token, and it worked perfectly. However, when I try to use google-oauth2 as the backend, I always get this message:

{  
   "error_description":"Backend responded with HTTP403: { "error":{  
      "errors":[  
         {  
            "domain":"usageLimits",
            "reason":"dailyLimitExceededUnreg",
            "message":"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
            "extendedHelp":"https://code.google.com/apis/console"
         }
      ],
      "code":403,
      "message":"Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
   }
}.",
"error":"invalid_request"
}

From my settings.py:

AUTHENTICATION_BACKENDS = (
    # Facebook OAuth2
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.facebook.FacebookOAuth2',

    # Google OAuth2
    'social.backends.google.GoogleOAuth2',

    # django-rest-framework-social-oauth2
    'rest_framework_social_oauth2.backends.DjangoOAuth2',

    # django
    'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '***'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '***'
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email',]

My request looks like this:

curl -v -X POST -d "grant_type=convert_token&client_id=<client_id_here>&client_secret=<client_secret_here>&backend=google-oauth2&token=<google_token_here>" http://localhost:8000/auth/convert-token

Have you seen anything like this?

Get user profile with the token response

Hi,

How could I add the user profile in the response from "auth/convert-token"?

I am performing the social login with Google+. "auth/convert-token" returns only:
{"expires_in":36000,"refresh_token":"z0y9RzwGMRat4MG28zNBMaNTCIxnjY","scope":"read write","access_token":"SFQQ3RyqiMLIgVR8l5xMzs7pmkHv1b","token_type":"Bearer"}

In the request header I have:
Authorization: Bearer SFQQ3RyqiMLIgVR8l5xMzs7pmkHv1b
But in the view, the request.user is "AnonymousUser".

Best regards,
Douglas

SSO Authentication with JWT

Hey,
I'm developing a mobile app and I want to use social authentication for Single Sign On. I want my user to log in using FB/Google ONLY ONCE in the app lifetime.

So what I want to do is:

  1. User logs in using the app to FB/Google.
  2. FB/Google returns an access_token
  3. The app sends this access_token to Django backend using POST request
  4. Django Backends find the user associated to this FB account or creates a new one using first name, last name and email from FB account
  5. Django returns a JWT token for further authentication with infinite lifetime
  6. The JWT is saved on the mobile application
  7. Next the app uses this JWT to authenticate the user and then no more FB log in is necessary

Can I do that with your package? How?

Error in README.rst

@PhilipGarnero Thank for this great library! In this section, there is a error:

curl -H "Authorization: Bearer <backend_name~~~~> <backend_token>" http://localhost:8000/route/to/your/view

it shouldn't put <backend_name> in this request.

Again, Thank so much for this great library!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.