Django DRF Sign-in with Apple

It’s time to implement Apple’s authentication system in a Django DRF project, because the login system from Google was implemented a long time ago and, in theory, there should have been no problems, but as it turned out, Apple There are certain interesting and not so special features, which I will write about below.

After reading the documentation, rummaging through the Internet on various resources, both Russian and English, I came to the conclusion that there is no clear implementation guide for such a powerful WEB development tool as Django DRF Sign in with Apple into the project, so that it would work out of the box.

In this article, I would like to try to correct the situation, and also, perhaps, to simplify life for many when introducing such a useful option as Sign in with Apple into a project written in Django REST framework.

  • For Google sign-in package was used https://github.com/wagnerdelima/drf-social-oauth2. It makes no sense to focus on installing and configuring the package, because the manual describes everything in detail, and there is also an example of authorization “by google“.

    It is perhaps worth noting that the authorization token release string for Google sign-in will look like this:

    curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token

    In the case of Apple sign in, everything remains the same, we only change the name of the backend to backend=apple-id and a request link to https://yourdomanname/api/auth/convert-token (path to your endpoint), according to this library social-auth-coreand the documentation is here.

  • We get the necessary credentials from Apple.

    Note: Apple sign-in requires an Apple Developer account.

    With that in mind, here are the steps you need to take to set up Apple Login.

    Setting up an Apple developer account.

    There are four things you need to integrate Sign-in with Apple into your application.

    • Service ID

    • Bundle ID

    • private key

    • Team ID

    The steps below will allow you to get this data, let’s get started.

    1. First you need to create an application ID at https://developer.apple.com/account/resources/certificates/list or you can just click here then go to the tab Identifiersclick +Near Identifiers

      • Select “App IDs” and click “continue”.

      • Select the “App” option and click “continue”.

      • Adding a description of your application to the field description. Then add your package id Bundle ID in format: com.domainname.appname

      • Go to “Capabilities” and enable Sign in with Apple .

      • Click on the “edit” button, select Enable as a primary App ID and then click “save”.

      • We press “continue”. We check all the entered information and, if everything is correct, click onRegister.

    2. Now we need to create a service ID.

      • Let’s go to the same pageas before, but now we choose Service IDsfrom the dropdown list on the right.

      • Identifiersclick sign + Near Identifiers.

      • We ask Description And Identifier.

      • Set the checkbox to Signin with apple and, press Configurechoose Primary App ID.

      • You will be prompted to select your Primary App ID (select the application that we created in the paragraph above).

      • Then add your application domain, click on + Near Website URLs.

        In field Domains and Subdomains enter the name of your domain, which requires authorization by AppleID. Here it should be noted that in this field it is necessary to enter only the domain name without https:// in the format sub.domainname.com Otherwise, you will then receive an error during authorization.

        In field Return URLs add a url that looks like this https://sub.domainname.com/authit must match the address where react app or any other application from “front”will request data from Apple.

      Note: Unlike Google, Apple does not allow format entries http://localhost:8000 V return urls, therefore, it will not be possible to connect this whole “case” to the local host and test it, Apple generally does not allow the use of an application without an SSL certificate, that is, only https://.

      • We save everything.

      • Verify that the information entered is correct and click Register.

    3. Let’s go back to page and go to tab Keys press +to add a new key (or go to new key registration page ).

      • Add a name to your key key name.

      • Set the checkbox to Signin with apple and press Configure.

      • Choose Primary App ID, as in point 2 and press save.

      • Check the correctness of the entered information and clickRegister.

      • Download the generated certificate.

  • It’s time to set up our application to Django DRFfor use with AppleID.

    We open our project, and in particular the file settings.py and change it like this:

    AUTHENTICATION_BACKENDS = [
      # Google OAuth2
      'social_core.backends.google.GoogleOAuth2',
      #Apple OAuth2
      'social_core.backends.apple.AppleIdAuth',
      #drf‑social‑oauth2
      'drf_social_oauth2.backends.DjangoOAuth2',
      #Django
      'django.contrib.auth.backends.ModelBackend',
    ]

    Next, you need to add data received from Apple:

    # Apple OAuth2
    SOCIAL_AUTH_APPLE_ID_CLIENT = 'com.domainname.service' # Берём в Services IDs со страницы IDENTIFIER, который мы создали в предыдущем пункте
    SOCIAL_AUTH_APPLE_ID_TEAM = 'K2232113' # Team ID, можно посмотреть на странице https://developer.apple.com/account/#/membership, прокручиваем вниз до Membership details, смотрим наш Team ID
    SOCIAL_AUTH_APPLE_ID_KEY = 'Y2P99J3N81K' # Ваш Key ID, смотрим на странице созданного нами ключа, из прошлого пункта
    SOCIAL_AUTH_APPLE_ID_SECRET = ”””
    Откройте свой файл ключа Apple, в любом текстовом редакторе, и поместите сюда всё содержимое, включая
    ‑--‑BEGIN PRIVATE KEY‑---
    ‑--‑END PRIVATE KEY‑--‑”””
    SOCIAL_AUTH_APPLE_ID_SCOPE = ['email', 'name']
    SOCIAL_AUTH_APPLE_ID_EMAIL_AS_USERNAME = True # Если нужно использовать email в качестве имени пользователя

    Note: Going through all these steps with setting up a Django DRF application, I mean that you already have all the packages from the first point installed, the migrations are all done, and the necessary imports and settings are added, in accordance with the guide this package, as well as created client_id And client_secret.

  • Forming a request link in Apple.

    Having gone through all the preparatory stages, it is time to form "верный" request to Applein order to receive id_token authorization from Apple and pass it to the server to complete the authorization in your WEB application.

    Note: Don’t let the title fool you id_tokenwhile studying documentation by API from Applein fact it JSON Web Token signed Apple and containing user information.

    For getting id_token from Apple you can use this library if your frontend is written in React.

    Release link itself id_token should look like this:

    https://appleid.apple.com/auth/authorize?client_id=com.domainname.service&redirect_uri=https://sub.domainname.com/auth&state=&response_type=code id_token&response_mode=form_post&scope=email

    Note: client_id And redirect_uri we asked in paragraph 2when they created Service ID. Also, please include in your request scope=emailotherwise when decoding id_token will return an error that the email was not found (Apple will simply not put this data in id_token). But if you later change the link and add scope=emailthen nothing will change for the user who has already tried to authorize, his email will not be in id_token until he deletes the application in his account Apple and will not re-enter using the correct release link id_token.

    Here is an example of what we get fromApple:

    We get id_token from Apple.

    We get id_token from Apple.

  • Server Side Authorization Django DRF.

    Here we come to the final stage, for the sake of which we performed all the previous manipulations. As I said in paragraph 1we just need to send POST request for address https://yourdomanname/api/auth/convert-tokenthe answer of which will be Bearer Tokenwhich we will use every time our API is called.

    Release line Bearer Token on the server side will be formed according to the following principle:

    grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=apple-id&token=<id_token>

    Note: Media type request must be application/x-www-form-urlencoded

    Here is an example of what we will get after successful authentication on the server side:

    Response from Django API

    Response from Django API

  • I hope this material will be useful to someone. Thank you for reading the text to the end!

    Similar Posts

    Leave a Reply

    Your email address will not be published. Required fields are marked *