Giter Site home page Giter Site logo

wagnerdelima / drf-social-oauth2 Goto Github PK

View Code? Open in Web Editor NEW
259.0 259.0 33.0 840 KB

drf-social-oauth2 makes it easy to integrate Django social authentication with major OAuth2 providers, i.e., Facebook, Twitter, Google, etc.

Home Page: https://drf-social-oauth2.readthedocs.io/en/latest/

License: MIT License

Python 96.15% Dockerfile 0.54% Shell 0.71% Makefile 1.18% Batchfile 1.42%
auth-provider authentication authorization django django-rest-framework drf drf-oauth2 jwt-auth oauth oauth2 openid openid-provider permission python python3 social-login

drf-social-oauth2's People

Contributors

afonsocarlos avatar ashishmohite avatar bmpenuelas avatar c-bata avatar denizdogan avatar dependabot[bot] avatar deshraj avatar dlintin avatar dutkiewicz avatar grahamhealy20 avatar hugocore avatar jperelli avatar knaperek avatar marcelchastain avatar mizvyt avatar oudeismetis avatar philipgarnero avatar puneetagg avatar ronlut avatar ryan-blunden avatar smithumble avatar snyk-bot avatar t16n avatar tamayonauta avatar tejon-melero avatar trumpet2012 avatar vbabiy avatar virako avatar wagnerdelima avatar zubrzubr 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

drf-social-oauth2's Issues

Misleading documentation ?

Hi. I've some difficulties following the README and the Social part.

As far as I understand, the first part is for "normal" (non-social) auth. It says one must create an app in the Django admin. There are actually various places, but I firgured out it is in the Django OAuth Toolkit › Applications section.

The social part is unclear to me. I managed to make a login through GitHub work, but without any additional application added in the admin (as stated by the README). The ID and Key inside the settings.py file were sufficient to achieve the result (as far as I can tell).

Am I missing something ? Thanks a lot for your help.

New columns added in UserSocialAuth for dependency social-auth-app-django 3.2.0

The issue is based off of the original repo, but the owner seemed to have stopped maintaining it. Adding issue here instead.

Basically I was using django-rest-framework-social-oauth2 for Google OAuth2, and starting about early June I started getting this error:

ProgrammingError
column social_auth_usersocialauth.created does not exist
LINE 1: ..."uid", "social_auth_usersocialauth"."extra_data", "social_au...
                                                             ^

Some investigation led me to realize that the dependency social_auth_usersocialauth v3.2.0 added two new columns to the UserSocialAuth model, namely created and modified. However, the requirements for this allows >=3.1.0, which hid the breaking change. Partly was my fault for not realizing my app updated to a newer version of social_auth_usersocialauth, but would be nice if future releases can pin specific versions of dependencies.

Azure AD B2C Authentication

Hey all,

Has anyone successfully authenticated against Azure AD B2C? The social_core module does in fact have a azuread_b2c file, but I cannot seem to figure out how to implement this. Is there any documentation out there on how to set this up? Will gladly put some documentation together if someone can point me in the right direction.

Implement SSO with drf-social-oauth2

Hello everyone,

I am using the library to allow external users to use my django rest framework API.

I would like to register the external user if he is not in the database and connect him if he is.
Is it possible to implement Single Sign On with the library ?

Thank you in advance for helping me.
Nicolas

NoReverseMatch for complete

I successfully got access token using convert-token api point but after looks like I can not use it. It fails during SocialAuthentication runtime when it tries to reverse url pattern:

backend = load_backend(
    strategy, backend, reverse(f'{NAMESPACE}:complete', args=(backend,)),
)

Exception:

django.urls.exceptions.NoReverseMatch: Reverse for 'complete' not found. 'complete' is not a valid view function or pattern name.

I included urls:

path(f'{API_PREFIX}auth/', include('users.social_urls', namespace='social')),

Note, that code in users.social_urls is the same like in library, I just need to inherit some views to specify swagger response and request schemes.
And also I don't have any redirect urls, my flow is:

  1. Get facebook token using convert-token api point.
  2. Create user
  3. Use that token on protected endpoints (permissions.IsAuthenticated)

Does someone has the same issue?

Auth/convert-token returns 500 internal server error when email is already registered.

Auth/convert-token returns 500 internal server error when user tries to create an account with social login i.e Facebook...

And when I checked the reason, it was because client has created an account already in my site with the same email he is registering his Facebook account with.

So it is a duplicated email..

Would you update the app with a status 200 response for this case?

Or kindly support me to do it my self..

Thanks in advance

Dead Twitch API v5, there is a code to replace it with new one

So I stumbled upon an issue making authorization through Twitch API, because in this project it is using old Twitch API v5, that is no longer available. I've looked into the project's code, found twitch.py file, and modified it so it works now.

File is located at site-packages of venv, where you installed drf-social-oauth2 library: "site-packages/social_core/backends/twitch.py"

Don't forget to add Twitch app credentials to your settings.py file. Here is the code to modify twitch.py, so it will work with new Twitch API:

from .oauth import BaseOAuth2
from django.conf import settings


class TwitchOAuth2(BaseOAuth2):
    """Twitch OAuth authentication backend"""
    name = 'twitch'
    ID_KEY = '_id'
    AUTHORIZATION_URL = 'https://id.twitch.tv/oauth2/authorize'
    ACCESS_TOKEN_URL = 'https://id.twitch.tv/oauth2/token'
    ACCESS_TOKEN_METHOD = 'POST'
    DEFAULT_SCOPE = ['user:read:email']
    REDIRECT_STATE = False


    def get_user_id(self, details, response):
        return response['data'][0]['id']

    def get_user_details(self, response):
        data = response['data'][0]

        return {
            'username': data['login'],
            'email': data['email'],
            'first_name': '',
            'last_name': '',
        }


    def user_data(self, access_token, *args, **kwargs):
        return self.get_json(
            'https://api.twitch.tv/helix/users/',
            headers={'Authorization': f'Bearer {access_token}', 'client-id': settings.SOCIAL_AUTH_TWITCH_KEY,}

        )

Old commit history

It is a bit unfortunate if this library looses the old contribution history.

Any chance you could re-create it with full history, in order to give credit to the previous contributors

ORCID OAuth /login error: 'social' is not a registered namespace

@wagnerdelima Not sure what I have done wrong here with the setup, but I have tried to use:

    path(
        '{}/oauth/'.format(ASENCIS_API_v1),
        include('drf_social_oauth2.urls', namespace='drf')
    ),
    ...

and also:

    path(
        '{}/oauth2/'.format(ASENCIS_API_v1),
        include('drf_social_oauth2.urls'),
        name='social'
    ),
    ...

In my urls.py.

However, I receive the following error:

django.urls.exceptions.NoReverseMatch: 'social' is not a registered namespace

I'm trying to begin an OAuth process for the ORCID social backend...

Really not sure what I have done wrong here?

How to integrate google authentication?

When adding a new app to google, using google developers console, it makes me generate Oauth2 client ID per platform.

So for example, android app will have different client ID than ios app.

But both those apps need to work with the Django REST API I'm working on. And they both need "login with google" feature.

The google config needs just one key, like:

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'key goes here'

How do I configure this if I have multiple oauth2 client IDs (one for android, one for ios, etc.)?

Uploading screen from google dev console to illustrate the issue

Screenshot at 2021-02-01 19-28-42

How to implement signing with apple id?

I had followed this setup to implement signing with apple
https://python-social-auth.readthedocs.io/en/latest/backends/apple.html

but when i send the request from the IOS app i get this

[11/Nov/2020 10:16:02] "OPTIONS /oauth/convert-token/ HTTP/1.1" 200 0
Internal Server Error: /oauth/convert-token/
Traceback (most recent call last):
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\api_jws.py", line 186, in _load
header_data = base64url_decode(header_segment)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\utils.py", line 42, in base64url_decode
return base64.urlsafe_b64decode(input)
File "c:\users\euli\appdata\local\programs\python\python37\lib\base64.py", line 133, in urlsafe_b64decode
return b64decode(s)
File "c:\users\euli\appdata\local\programs\python\python37\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (33) cannot be 1 more than a multiple of 4

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\braces\views_forms.py", line 30, in dispatch
return super(CsrfExemptMixin, self).dispatch(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework_social_oauth2\views.py", line 70, in post
url, headers, body, status = self.create_token_response(request._request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauth2_provider\views\mixins.py", line 124, in create_token_response
return core.create_token_response(request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauth2_provider\oauth2_backends.py", line 145, in create_token_response
headers, extra_credentials)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauthlib\oauth2\rfc6749\endpoints\base.py", line 116, in wrapper
return f(endpoint, uri, *args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework_social_oauth2\oauth2_endpoints.py", line 60, in create_token_response
request, self.default_token_type)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauthlib\oauth2\rfc6749\grant_types\refresh_token.py", line 60, in create_token_response
self.validate_token_request(request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework_social_oauth2\oauth2_grants.py", line 94, in validate_token_request
user = backend.do_auth(access_token=request.token)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\social_core\backends\apple.py", line 149, in do_auth
decoded_data = self.decode_id_token(jwt_string)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\social_core\backends\apple.py", line 107, in decode_id_token
kid = jwt.get_unverified_header(id_token).get('kid')
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\api_jws.py", line 166, in get_unverified_header
headers = self._load(jwt)[2]
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\api_jws.py", line 188, in _load
raise DecodeError('Invalid header padding')
jwt.exceptions.DecodeError: Invalid header padding
[11/Nov/2020 10:16:02] "POST /oauth/convert-token/ HTTP/1.1" 500 24653
Internal Server Error: /oauth/convert-token/
Traceback (most recent call last):
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\api_jws.py", line 186, in _load
header_data = base64url_decode(header_segment)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\utils.py", line 42, in base64url_decode
return base64.urlsafe_b64decode(input)
File "c:\users\euli\appdata\local\programs\python\python37\lib\base64.py", line 133, in urlsafe_b64decode
return b64decode(s)
File "c:\users\euli\appdata\local\programs\python\python37\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (33) cannot be 1 more than a multiple of 4

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\braces\views_forms.py", line 30, in dispatch
return super(CsrfExemptMixin, self).dispatch(*args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework_social_oauth2\views.py", line 70, in post
url, headers, body, status = self.create_token_response(request._request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauth2_provider\views\mixins.py", line 124, in create_token_response
return core.create_token_response(request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauth2_provider\oauth2_backends.py", line 145, in create_token_response
headers, extra_credentials)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauthlib\oauth2\rfc6749\endpoints\base.py", line 116, in wrapper
return f(endpoint, uri, *args, **kwargs)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework_social_oauth2\oauth2_endpoints.py", line 60, in create_token_response
request, self.default_token_type)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\oauthlib\oauth2\rfc6749\grant_types\refresh_token.py", line 60, in create_token_response
self.validate_token_request(request)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\rest_framework_social_oauth2\oauth2_grants.py", line 94, in validate_token_request
user = backend.do_auth(access_token=request.token)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\social_core\backends\apple.py", line 149, in do_auth
decoded_data = self.decode_id_token(jwt_string)
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\social_core\backends\apple.py", line 107, in decode_id_token
kid = jwt.get_unverified_header(id_token).get('kid')
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\api_jws.py", line 166, in get_unverified_header
headers = self._load(jwt)[2]
File "C:\Users\Euli.virtualenvs\backend-WVgn4dJp\lib\site-packages\jwt\api_jws.py", line 188, in _load
raise DecodeError('Invalid header padding')
jwt.exceptions.DecodeError: Invalid header padding
[11/Nov/2020 10:16:03] "POST /oauth/convert-token/ HTTP/1.1" 500 24653

I couldn't find another documentation of how to implement

Additional body parameters for convert-token

Hi Everyone! I'm trying to implement apple id and facebook auth for rest api app.
My custom user model has two additional fields: birthplace and birthday. I want to populate those fields if facebook or apple auth is succeed, is that possible to pass additional params with convert-token request?

TypeError: create_user() missing 2 required positional arguments: 'birthday' and 'birthplace'

It would be also nice to have an option to display proper swagger api call with body example. Thanks

Replace 30 Character Token with JWT for Access & Refresh Token

Could you create the access and refresh tokens as JWT format instead of the standard 30 character token?

I have found this library https://pypi.org/project/python-jwt/ to be excellent on other projects in flask etc as it enables you to create the JWT token in lots of different signing algorithms including PS256.

Is this possible as the project stands is my first question? Secondly if not. How difficult is it to update so it does use the JWT format with this library to generate the access and refresh tokens?

Invalid token response

while using the token returned from the app in my authorized requests I got this response:

HTTP/1.1 401 Unauthorized
Allow: POST, OPTIONS
Content-Length: 27
Content-Type: application/json
Date: Mon, 22 Mar 2021 02:07:47 GMT
Server: WSGIServer/0.2 CPython/3.6.9
Vary: Accept
WWW-Authenticate: Token
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
"detail": "Invalid token."
}

I tried both access token and refresh token

However the user is registered fine and added to my custom users models and django social model

Thanks in advance

kwargs['response']['orcid']) KeyError: 'response'

@wagnerdelima I'm trying to integrate this package with the ORCID backend: https://python-social-auth.readthedocs.io/en/latest/backends/orcid.html

However, I'm seeing a number of issues.

When I come to perform a convert-token action, e.g.,

curl -X POST -d "grant_type=convert_token&client_id=APP-V6L0CRR65TST7UW1&client_secret=b99946ac-45c0-4c5c-a19e-e0c730e5f109&backend=orcid&token=3bgrab7d-4510-48f4-86c5-76f2f50a6aba" http://0.0.0.0:8000/auth/convert-token

I'm seeing the following error:

web_1          |   File "/usr/local/lib/python3.8/site-packages/drf_social_oauth2/oauth2_endpoints.py", line 91, in create_token_response
web_1          |     return grant_type_handler.create_token_response(
web_1          |   File "/usr/local/lib/python3.8/site-packages/oauthlib/oauth2/rfc6749/grant_types/refresh_token.py", line 60, in create_token_response
web_1          |     self.validate_token_request(request)
web_1          |   File "/usr/local/lib/python3.8/site-packages/drf_social_oauth2/oauth2_grants.py", line 100, in validate_token_request
web_1          |     user = backend.do_auth(access_token=request.token)
web_1          |   File "/usr/local/lib/python3.8/site-packages/social_core/utils.py", line 251, in wrapper
web_1          |     return func(*args, **kwargs)
web_1          |   File "/usr/local/lib/python3.8/site-packages/social_core/backends/oauth.py", line 410, in do_auth
web_1          |     data = self.user_data(access_token, *args, **kwargs)
web_1          |   File "/usr/src/app/api/authentication/backends/orcid.py", line 66, in user_data
web_1          |     kwargs['response']['orcid']),

The error seems to be coming from line 64 of here: https://github.com/python-social-auth/social-core/blob/master/social_core/backends/orcid.py

Any ideas on why this is happening?

Please publish this package to pypi

:)
How can I help to make it happen? do you need a setup.py or something? Maybe I can publish and then transfer ownership to you. I'll investigate

Google Oauth

Hi,

While using the lib, I am getting this error for Google-Oauth2

My post request to /convert-token is :
{
"grant_type": "convert_token",
"client_id": "django-app-client-id",
"client_secret": "django-app-client secret",
"backend": "google-oauth2",
"token": "facebook-access-token"
}

When making the post request I get the error :

HTTP 400 Bad Request
Allow: POST, OPTIONS
Cache-Control: no-store
Content-Type: application/json
Pragma: no-cache
Vary: Accept

{
"error": "access_denied",
"error_description": "Your credentials aren't allowed"
}

Getting error while the user is disabled(is_active=False)

works perfectly While users login with the Facebook first time. in some cases, admin can disable the users(is_active=False).

Users can't log in with Facebook after disabling by admin. getting error NoneType

[Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 
'NoneType'>`](url)

Email address must be unique in order to add a new user.

I have created an app with both google and facebook auth in it, I tried accessing from the same email address facebook account and same email address google acount, what I now see is that there are two separate accounts created in the django admin and both of them have same email.
I want to void this situation and return some error saying that this account is already been registered.
How do I do that?

Linkedin cannot convert token

I was able to receive an authorization_code and convert it to access token. However, when I pass it to http://localhost:8000/auth/convert-token/ I got an error
{
"error": "invalid_request",
"error_description": "Backend responded with HTTP403: {"serviceErrorCode":100,"message":"Not enough permissions to access: GET /me","status":403}."
}

I passed as a parameter token, backend - linkedin-oauth2, grant_type: convert_token, client_id and client_secret

How many Applications [Oauth Toolkit] are we meant to create?

Greetings!

First, thank you to those who have helped contribute to the repo, It's been an excellent find for my projects. I'm a little confused on how many Applications inside the Django admin page are meant to be created?

To my understanding, each method of social authentication via Google, Facebook, Twitter, etc... requires a new Application to be made. Based on the three platforms I just stated previous, that would require 3 different applications to be generated through Oauth Toolkit section in Django Admin page.

Is my understanding correct? If not I would greatly appreciate some clarity for the use-case for generating applications with the Oauth Toolkit.

Many thanks! 👍

Max retries exceeded with url: /oauth2/v3/userinfo

I'm experiencing issues on the server-side of my application that are causing all sorts of slowdowns. This is unrelated to Django but, apparently, these issues are also causing logins to fail.

My app uses drf-social-oauth2 to allow users to sign in using their google account. For the past 12 hours, any request made to the endpoing convert_token (which always worked fine until today), such as this:

{"grant_type":"convert_token","client_id":"...","client_secret":"...","backend":"google-oauth2","token":"..."}

Causes the server to respond after several seconds with:

HTTP 400 Bad Request
Allow: POST, OPTIONS
Cache-Control: no-store
Content-Type: application/json
Pragma: no-cache
Vary: Accept

{
    "error": "access_denied",
    "error_description": "Authentication failed: HTTPSConnectionPool(host='www.googleapis.com', port=443): Max retries exceeded with url: /oauth2/v3/userinfo (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f155526e310>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))"
}

Like I mentioned, I realize the cause of this is a problem on my end but, is there anything that can be done on drf-social-oauth2 to circumvent this? I read there's an issue with retries, and it makes me think the request ends up timing out or something.

Are there any modifications that can be made to the settings to allow for a looser limit on retries, working around the issue temporarily?

"Invalid backend parameter" for AzureAD Tenant

Been struggling to get this implemented and find the documentation pretty vague. I'd like to help improve it if I can get this working.

Related documentaiton:

https://python-social-auth.readthedocs.io/en/latest/backends/azuread.html

# settings.py
INSTALLED_APPS = [
    ...
    'drf_social_oauth2',
    'oauth2_provider',
    'rest_framework',
    'social_django',
    ...
]

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 
        'drf_social_oauth2.authentication.SocialAuthentication',
    ),
    ...
}

SOCIAL_AUTH_POSTGRES_JSONFIELD = True

SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = '<azure_client_id>'
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = '<azure_client_secret>'
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = '<azure_tenant_id>'

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'drf_social_oauth2.backends.DjangoOAuth2',
    'social_core.backends.azuread_tenant.AzureADTenantOAuth2',
)
# urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('api/admin/', admin.site.urls),
    path('api/users/auth/azuread/', include('drf_social_oauth2.urls', namespace='drf')),
    path('api/users/', include('users.urls', namespace='users')),
]

And then this is what I get when I try to run a POST request in Postman:

image

I've tried:

  • backend=azuread_tenant
  • backend=AzureADTenantOAuth2
  • backend=azureadtenantoauth2

Really isn't clear what the values of backend need to be, what are acceptable, where they can be found, or if it is an arbitrary designation.

Also, in these curl requests:

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

It seems like <client_id> and <client_secret> are the values for the App in Django Admin, and not for the backend you are using (those are declared in the settings.py).

There isn't a convert_token type for the App in Django Admin, so it is unclear what the Authorization grant type should be set at for the App in there.

Also, token= isn't really discussed at all in the "Integration Examples", nor in the python-social-auth, or oauth2-provider... so not sure if this is a value that is supposed to be generated by the backend provider when you are setting up the integration on their platform, or if it is something that is returned from the OAuth2 request and the /convert-token is a second step...

At any rate, the primary issue is the invalid backend parameter.

auth/token POST request --Invalid credentials given--

Hey there!
First of all thanks a lot you have done wonderful job! 🙏🏽
I'm running to en issue when I try to login through http://127.0.0.1:8000/auth/token
I use the exact username and password, client id and secret are copied from admin panel
Screen Shot 2021-06-23 at 15 36 34

For example http://127.0.0.1:8000/auth/convert-token works perfectly fine
Screen Shot 2021-06-23 at 15 41 29

Github - convert_token

Hi there,
how the github implementation is supposed to work?
Examples that i found all relate to Google or Facebook where those providers return an accessToken while Github returns a code.
At the moment i'm stuck at the point where i have the code from Github and i would convert into a token, so i do my POST request like this:

POST http://localhost:8000/auth/convert-token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=convert_token
&client_id=aIK0dQjlOlDe9UwV0pZfR2DlEBX8HrqdqhSD1iNr
&client_secret=RXc9lTKqadPixO6ZoNiC8TWXPb7iLnQ5VeSMu0TXNkrnMVGynhHiDwzlNW6B1OftRpZ6nvWjpPiu2cA1aV0Iv7vgugwbXp1FOOCvnWHFSTeZbYrWxAbiX4dkTM7pVfEC
&backend=github
&token=35fa2fe846c3f6867e63 <- code from Github

(client_id e secret comes from django admin)

DRF response:

HTTP/1.1 400 Bad Request

{
  "error": "access_denied",
  "error_description": "Your credentials aren't allowed"
}

Below my settings

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_django',
'drf_social_oauth2',
]

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_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'drf_social_oauth2.authentication.SocialAuthentication',
),
}

AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2',
'drf_social_oauth2.backends.DjangoOAuth2',
'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_GITHUB_KEY = 'my key'
SOCIAL_AUTH_GITHUB_SECRET = 'my secret'

SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)

Sure i'm missing something.

Best regards,
Mattia

Revoke Token & Invalidate Sessions Status Code 415?

I'm attempting to POST to the revoke-token endpoint, here is a breakdown of the request headers:

Screenshot 2021-03-11 at 11 40 36

However, the response is coming back with a status code of 415, with the following details:

Unsupported media type "application/json, application/json;charset=utf-8" in request.

Could anyone advise why we're seeing these issues for these endpoints? What is the correct content type?

Edit User Model or View for registering

Since Facebook has stopped providing username due to privacy concerns.
Issue: User created, but Username is some long ID number.

Now I want to edit the register user view so I can create a unique username from views. If anyone can help me in this issue.
Screenshot 2021-06-25 at 15 44 33

Invalid backend when converting token on server

Hey there! First of all thank you for keeping this project alive.

I've been struggling a little bit to get things working on the server. When running locally it works like a charm:

image

But when I try to do the same on the server (over https) I'm getting the Invalid backend parameter error:

image

It's the same error if I try with facebook or google-oauth2 backends.

Here are the configs:

DEBUG = False

CORS_ORIGIN_ALLOW_ALL = DEBUG

CORS_ALLOWED_ORIGINS = ['http://localhost:4201', 'http://localhost:8000',
                        'https://desenv.valuemachine.com.br', 'https://valuemachine.com.br']

ALLOWED_HOSTS = ['localhost',
                 'desenv.valuemachine.com.br', 'valuemachine.com.br']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'django_filters',
    'drf_yasg',
    'oauth2_provider',
    'social_django',
    'drf_social_oauth2',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mercado_financeiro.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        '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_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

REST_FRAMEWORK = {
    'PAGE_SIZE': 20,

    'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',

    'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.JsonApiPageNumberPagination',
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
        'drf_social_oauth2.authentication.SocialAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework_json_api.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_json_api.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    'DEFAULT_METADATA_CLASS': 'rest_framework_json_api.metadata.JSONAPIMetadata',
    'DEFAULT_FILTER_BACKENDS': [
        'rest_framework_json_api.filters.QueryParameterValidationFilter',
        'rest_framework_json_api.filters.OrderingFilter',
        'rest_framework_json_api.django_filters.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    'SEARCH_PARAM': 'filter[search]',
    'ORDERING_PARAM': 'sort',
    'TEST_REQUEST_RENDERER_CLASSES': [
        'rest_framework_json_api.renderers.JSONRenderer',
    ],
    'TEST_REQUEST_DEFAULT_FORMAT': 'vnd.api+json'
}

AUTHENTICATION_BACKENDS = (
    'social_core.backends.facebook.FacebookAppOAuth2',
    'social_core.backends.facebook.FacebookOAuth2',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.linkedin.LinkedinOAuth2',
    'drf_social_oauth2.backends.DjangoOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

# Facebook configuration
SOCIAL_AUTH_FACEBOOK_KEY = 'xxxx'
SOCIAL_AUTH_FACEBOOK_SECRET = 'xxxx'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
    'fields': 'id, name, email'
}

# Google configuration
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxx'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxx'

SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

Have you ever had this issue? Do you have a clue about it? I'm very confused about this because it was supposed to work just fine since it is working when I am running locally.

Social Auth API testing from mobile

I am having hard time to figure out step wise process to test drf-social-oauth2 with Postman. I exposed APIs for my mobile application and I need to signup/register/login users from my mobile using the API.

If someone can help me to figure out workflow step wise for testing on Postman I will be really thankful.

Cheers.

Access convert-token from mobile app

I have been using this tool and I find it to be great, I currently use it with a mobile app, I use the convert-token url to get a token and thus give my users access to the API, I just wanted to know if it's a good idea to store the generated client_id and client_secret in the mobile app ?, It seems like a bad practice to me, any suggestions ?

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.