Package: rest-social-auth
Django REST social authOAuth signin with django rest framework.Requirementspython (3.7, 3.8, 3.9, 3.10, 3.11, 3.12)django (3.2, 4.1, 4.2, 5.0)djangorestframework (>=3.9, <4.0)social-auth-core (>=4.3, <5.0)social-auth-app-django (>=5.0, <6.0)[optional] djangorestframework-simplejwt (>=5.0.0)[optional] django-rest-knox (>=4.0.0, <5.0.0)Release notesHereMotivationTo have a resource, that will do very simple thing:
take theoauth codefrom social provider (for example facebook)
and return the authenticated user.
That's it.I can't find such util fordjango rest framework.
There are packages (for exampledjango-rest-auth), that takeaccess_token, not thecode.
Also, i've used to work with awesome librarypython-social-auth,
so it will be nice to use it again (now it is split intosocial-coreandsocial-app-django). In fact, most of the work is done by this package.
Current util brings a little help to integrate django-rest-framework and python-social-auth.Quick startInstall this package to your python distribution:pipinstallrest-social-authDo the settingsInstall appsINSTALLED_APPS=(...'rest_framework','rest_framework.authtoken',# only if you use token authentication'social_django',# django social auth'rest_social_auth',# this package'knox',# Only if you use django-rest-knox)social auth settings, lookdocumentationfor more detailsSOCIAL_AUTH_FACEBOOK_KEY='your app client id'SOCIAL_AUTH_FACEBOOK_SECRET='your app client secret'SOCIAL_AUTH_FACEBOOK_SCOPE=['email',]# optionalSOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS={'locale':'ru_RU'}# optionalAUTHENTICATION_BACKENDS=('social_core.backends.facebook.FacebookOAuth2',# and maybe some others ...'django.contrib.auth.backends.ModelBackend',)Also lookoptional settingsavaliable.Make sure everything is up do datepythonmanage.pymigrateInclude rest social urls (choose at least one)4.1session authenticationpath('api/login/',include('rest_social_auth.urls_session')),4.2token authenticationpath('api/login/',include('rest_social_auth.urls_token')),4.3jwt authenticationpath('api/login/',include('rest_social_auth.urls_jwt_pair')),or / andpath('api/login/',include('rest_social_auth.urls_jwt_sliding')),4.4knox authenticationpath('api/login/',include('rest_social_auth.urls_knox')),You are ready to login usersFollowing examples are for OAuth 2.0.5.1 session authenticationPOST /api/login/social/session/input:{
      "provider": "facebook",
      "code": "AQBPBBTjbdnehj51"
  }output:{
      "username": "Alex",
      "email": "user@email.com",
      // other user data
  }

  + session id in cookies5.2 token authenticationPOST /api/login/social/token/input:{
      "provider": "facebook",
      "code": "AQBPBBTjbdnehj51"
  }output:{
      "token": "68ded41d89f6a28da050f882998b2ea1decebbe0"
  }POST /api/login/social/token_user/input:{
      "provider": "facebook",
      "code": "AQBPBBTjbdnehj51"
  }output:{
      "username": "Alex",
      "email": "user@email.com",
      // other user data
      "token": "68ded41d89f6a28da050f882998b2ea1decebbe0"
  }5.3 jwt authentication (usingdjango-rest-framework-simplejwt)POST /api/login/social/jwt-pair/POST /api/login/social/jwt-pair-user/Similar to token authentication, but token is JSON Web Token.SeeJWT.iofor details.To use it, django-rest-framework-simplejwt must be installed.Forjwt-pair, the response will include additional "refresh" token:{"token":"...","refresh":"..."}Or sliding JWT token:POST /api/login/social/jwt-sliding/POST /api/login/social/jwt-sliding-user/Checkdocs of simplejwtfor pair/sliding token difference.Note.django-rest-framework-simplejwtdoesn't work on python3.65.4 knox authenticationPOST /api/login/social/knox/POST /api/login/social/knox_user/Similar to token authentication, but token is Django Rest Knox Token.To use it,django-rest-knoxmust be installed.User model is taken fromsettings.AUTH_USER_MODEL.At input there is also non-required fieldredirect_uri.
If given, server will use this redirect uri in requests, instead of uri
got from settings.
This redirect_uri must be equal in front-end request and in back-end request.
Back-end will not do any redirect in fact.It is also possible to specify provider in URL, not in request body.
Just append it to the url:POST /api/login/social/session/facebook/Don't need to specify it in body now:{
     "code": "AQBPBBTjbdnehj51"
 }Provider defined in URL has higher priority than provider in body.
If both are specified - provider will be taken from URL.OAuth 2.0 workflow with rest-social-authFront-end need to know following params for each social provider:client_id# only in case of OAuth 2.0, id of registered application on social service providerredirect_uri# to this url social provider will redirect with codescope=your_scope# for example emailresponse_type=code# same for all oauth2.0 providersFront-end redirect user to social authorize url with params from previous point.User confirms.Social provider redirects back toredirect_uriwith paramcode.Front-end now ready to login the user. To do it, send POST request with provider name and code:POST /api/login/social/session/with data (form data or json)provider=facebook&code=AQBPBBTjbdnehj51Backend will either signin the user, either signup, either return error.Sometimes it is more suitable to specify provider in url, not in request body.
It is possible, rest-social-auth will understand that.
Following request is the same as above:POST /api/login/social/session/facebook/with data (form data or json)code=AQBPBBTjbdnehj51OAuth 1.0a workflow with rest-social-authFront-end needs to make a POST request to your backend with the provider name ONLY:POST /api/login/social/with data (form data or json):provider=twitterOr specify provider in url, in that case data will be empty:POST /api/login/social/twitterThe backend will return a short-livedoauth_tokenrequest token in the response.  This can be used by the front-end to perform authentication with the provider.User confirms.  In the case of Twitter, they will then return the following data to your front-end:{
   "redirect_state":  "...bHrz2x0wy43",
   "oauth_token"   :  "...AAAAAAAhD5u",
   "oauth_verifier":  "...wDBdTR7CYdR"
 }Front-end now ready to login the user. To do it, send POST request again with provider name and theoauth_tokenandoauth_verifieryou got from the provider:POST /api/login/social/with data (form data or json)provider=twitter&oauth_token=AQBPBBTjbdnehj51&oauth_verifier=wDBdTR7CYdRBackend will either signin the user, or signup, or return an error.
Same as in OAuth 2.0, you can specify provider in url, not in body:POST /api/login/social/twitterThis flow is the same as described insatellizer. This angularjs module is used in example project.rest-social-auth purposeAs we can see, our backend must implement resource for signin the user.Django REST social auth provides means to easily implement such resource.List of oauth providersOAuth 1.0 and OAuth 2.0 providers are supported.Lookpython-social-authfor full list.
Name of provider is taken from correspondingbackend.nameproperty of
particular backed class in python-social-auth.For example forfacebook backendwe see:class FacebookOAuth2(BaseOAuth2):
    name = 'facebook'Here are some provider names:Providerprovider nameFacebookfacebookGooglegoogle-oauth2Vkontaktevk-oauth2InstagraminstagramGithubgithubYandexyandex-oauth2TwittertwitterOthers...SettingsREST_SOCIAL_OAUTH_REDIRECT_URIDefault:'/'Defines redirect_uri. This redirect must be the same in both authorize request (made by front-end) and access token request (made by back-end) to OAuth provider.To override the relative path (url path or url name are both supported):REST_SOCIAL_OAUTH_REDIRECT_URI = '/oauth/redirect/path/'
  # or url name
  REST_SOCIAL_OAUTH_REDIRECT_URI = 'redirect_url_name'Note, in case of url name, backend name will be provided to url resolver as argument.REST_SOCIAL_DOMAIN_FROM_ORIGINDefault:TrueSometimes front-end and back-end are run on different domains.
For example frontend at 'myproject.com', and backend at 'api.myproject.com'.If True, domain will be taken from request origin, if origin is defined.
So in current example domain will be 'myproject.com', not 'api.myproject.com'.
Next, this domain will be joined with path fromREST_SOCIAL_OAUTH_REDIRECT_URIsettings.To be clear, suppose we have following settings (defaults):REST_SOCIAL_OAUTH_REDIRECT_URI = '/'
  REST_SOCIAL_DOMAIN_FROM_ORIGIN = TrueFront-end is running on domain 'myproject.com', back-end - on 'api.myproject.com'.
Back-end will use following redirect_uri:myproject.com/And with following settings:REST_SOCIAL_OAUTH_REDIRECT_URI = '/'
  REST_SOCIAL_DOMAIN_FROM_ORIGIN = Falseredirect_uri will be:api.myproject.com/Also look atdjango-cors-headersif such architecture is your case.REST_SOCIAL_OAUTH_ABSOLUTE_REDIRECT_URIDefault:NoneFull redirect uri (domain and path) can be hardcodedREST_SOCIAL_OAUTH_ABSOLUTE_REDIRECT_URI = 'http://myproject.com/'This settings has higher priority thanREST_SOCIAL_OAUTH_REDIRECT_URIandREST_SOCIAL_DOMAIN_FROM_ORIGIN.
I.e. if this settings is defined, other will be ignored.
Butredirect_uriparam from request has higher priority than any setting.REST_SOCIAL_LOG_AUTH_EXCEPTIONSDefault:TrueWhenFalsewill not log social auth authentication exceptions.REST_SOCIAL_VERBOSE_ERRORSDefault:FalseWhenTruethe API will return error message received from server. Can be potentially unsecure to turn it ON.SOCIAL_AUTH_STRATEGYDefault:'rest_social_auth.strategy.DRFStrategy'Overridestrategyfor python-social-auth.CustomizationFirst of all, customization provided by python-social-auth is also avaliable.
For example, use nice mechanism ofpipelineto do any action you need during login/signin.Second, you can override any method from current package.
Specify serializer for each view by subclassing the view.To do itdefine your own url:path('api/login/social/$', MySocialView.as_view(), name='social_login'),define your serializerfrom rest_framework import serializers
  from django.contrib.auth import get_user_model

  class MyUserSerializer(serializers.ModelSerializer):

      class Meta:
          model = get_user_model()
          exclude = ('password', 'user_permissions', 'groups')define viewfrom rest_social_auth.views import SocialSessionAuthView
  from .serializers import MyUserSerializer

  class MySocialView(SocialSessionAuthView):
      serializer_class = MyUserSerializerCheck the code of the lib, there is not much of it.ExampleThere is anexample project.clone repogitclonehttps://github.com/st4lk/django-rest-social-auth.gitrun example projectmakeIt is assumed, that you have:makedockeropenhttps://127.0.0.1:8000/in your browserNote:runsslserveris used instead of built-inrunserverto serve the project with TLS (aka SSL) certificate.
HTTPS is required by some social providers (facebook), without it they won't work.
The certificate will not be trusted by your system - that is expected.
Just tell your browser to proceed with this untrusted certificate - it is acceptable for development purposes.In Chrome browser it can look like this:step 1:imagestep 2:imageMore detailshere.Facebook, Google and Twitter auth should work, all secret keys are already set.Example project usessatellizerangularjs module.DevelopmentRun tests locallymaketestRun tests in all enviroments (can take some time)maketest-toxContributorsThanks to all contributors!Alexey Evseev,st4lkJames Keys,skolsuperAaron Abbott,aabmassGrigorii Eremeev,Budulianinshubham,shubh3794Deshraj Yadav,DESHRAJgeorgewhewell,georgewhewellAhmed Sa3d,zee93Olle Vidner,ovidnerMounirMesselmeni,MounirMesselmeniTuomas Virtanen,katajakasaJeremy Storer,storerjeremyJeffrey de Lange,jgadelangeJohn Vandenberg,jayvdbAnton_Datsik,AntonDatsikNetizen29,Netizen29Dipendra Raj Panta,Mr-DRPJD,jd-0001Harsh Patel,eelectronnDevid,sevdogAnton Yakovlev,sputnik5459Olivér Kecskeméty,KOliver94vainu-arto,vainu-artoMaxim De Clercq,maximdeclercqalicegilli,alicegillirest_social_auth release notesv8.3.0Pass request to authentication backendhttps://github.com/st4lk/django-rest-social-auth/pull/175v8.2.0Add support of Django 5.0Add support of Python 3.12v8.1.0Add support of Django 4.2Add support of Python 3.11v8.0.0Drop support of Python 3.6Drop support of Django 3.0, 3.1Add support of Django 4.1Add support of Python 3.10Allow customized implementations of djangorestframework-simplejwt token classAddREST_SOCIAL_VERBOSE_ERRORSsettingv7.0.0Add support of social-auth-app-django==5.xAdd support of Django 3.2Drop support of social-auth-app-django<5.0v6.0.1Fix processing error from social provider #144v6.0.0Add support of social-auth-core==4.0Add support of social-auth-app-django==4.0Drop support of Python 3.5Drop support of social-auth-core<4.0Drop support of social-auth-app-django<4.0v5.0.1Expect error without response during error handlingv5.0.0Update user serializer: exclude field only if it was defined in customer user modelInclude error message from social provider into HTTP response of APIUsepath()django function instead of deprecatedurl()Drop support of Django 1.11Drop support of Python 2.7Drop support of deprecateddjangorestframework-jwtdependencyAdd support of Django 3.1Issues: #137v4.2.0Take provider name from URL firstIssues: #121v4.1.0Allow to specify custom strategy for python-social-authv4.0.0Update supported version of django-rest-knox (>=4.0.0, <5.0.0). v4 has breaking changes.Allow to use token auth with OAuth1 without django session enabledIssues: #110v3.0.0Add Django 3.0 supportAdd Python 3.8 supportDrop Django 2.0, 2.1 supportFix facebook integration in example project: serve with fake TLS certificateIssues: #104, #106v2.2.0Update license, use MITAdd Django 2.2 supportFix customer redirect URI for OAuth1Cleanup knox integrationv2.1.0Use djangorestframework-simplejwt for JWT implementationDeprecate djangorestframework-jwtAdd python3.7 supportIssues: #74v2.0.2Make social-auth-core >=3.0 as mandatory dependencyv2.0.1Minor update of pypi deployment processv2.0.0Update social-auth-core dependency to at least 3.0.0Issues: #73v1.5.0Update minimal required version of social-auth-app-django to 3.1.0Minor updates in readmeAdd Django 2.1 supportDrop Django 1.10 supportDrop Python 3.4 supportIssues: #70v1.4.0Add django-rest-knox supportv1.3.1Fix Django 2.0 supportv1.3.0Add Django 2.0 supportDrop Django 1.8, 1.9 supportIssues: #58v1.2.0Add Python 3.6 and Django 1.11 supportIssues #54v1.1.0Update docsAdd new settingREST_SOCIAL_LOG_AUTH_EXCEPTIONSIssues #42v1.0.0Add Django 1.10 supportDrop Django 1.7 supportAdd social-auth-core, social-auth-app-django dependenciesDrop python-social-auth dependencyIssues: #33, #35, #37, #38v0.5.0Handle HttpResponses returned by the pipelineIssues: #28v0.4.4Log exceptions from python-social-authDon't use find_packages from setuptoolsIssues: #22, #25v0.4.3Fix queryset assert errorminor typo fixesIssues: #20v0.4.2Remove django.conf.urls.patterns from codeExclude modifing immutable datarefactor testsminor typo fixesIssues: #11, #17, #14v0.4.1Fix requirements.txt: allow django==1.9v0.4.0AddJSON Web Tokensusingdjangorestframework-jwtAdd Python 3.5 and Django 1.9 supportIssues: #6v0.3.1Explicitly set token authentication for token viewsv0.3.0Add support for Oauth1Add ability to override request parsingAllow to specify provider in urlDrop Python 2.6 and Django 1.6 supportIssues: #2, #3, #5v0.2.0Get domain from HTTP OriginAdd example of Google OAuth2.0Add manual redirect uri (front-end can specify it)Use GenericAPIView instead of APIViewMain serializer is output serializer, not inputUpdate docsMinor code fixesv0.1.0First version in pypi