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.
The steps below will allow you to get this data, let’s get started.
First you need to create an application ID at
https://developer.apple.com/account/resources/certificates/listor you can just click here then go to the tab
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 IDand then click “save”.
We press “continue”. We check all the entered information and, if everything is correct, click on
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.
We ask Description And Identifier.
Set the checkbox to
Signin with appleand, 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
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 appor any other application from “front”will request data from Apple.
Note: Unlike Google, Apple does not allow format entries
http://localhost:8000V 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
We save everything.
Verify that the information entered is correct and click
Add a name to your key key name.
Set the checkbox to
Signin with appleand press
Choose Primary App ID, as in point 2 and press
Check the correctness of the entered information and click
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
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
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.
Apple you can use this library if your frontend is written in React.
Release link itself id_token should look like this:
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 from
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.
Bearer Token on the server side will be formed according to the following principle:
Media type request must be
Here is an example of what we will get after successful authentication on the server side:
I hope this material will be useful to someone. Thank you for reading the text to the end!