Sign in with Apple for iOS App with Backend

Dmytro Hrebeniuk 🇺🇦
3 min readApr 29, 2021

Apple provides mechanism for sign in using Apple ID.

  • Adding supporting it for iOS application, this give easy way to create account for user.
  • Apple requires it for applications which use other social services for sign in.

Setup Apple ID in developer account.

First setup SignIn with Apple in application on https://developer.apple.com

Steps for setup for supporting “Sign In With Apple”

Then need generate key for SignIn with Apple

Steps to generate key and Social Id for Backend

iOS Application

For UI button I recommend use class ASAuthorizationAppleIDButton, because Apple has strict requirements.

For perform auth request iOS providing ASAuthorizationController

Code sample:

Then implementing protocols:

  • ASAuthorizationControllerPresentationContextProviding
  • ASAuthorizationControllerDelegate

Code sample:

iOS SDK provide accessCode, which you can use on backend side.

Moment*: email and fullName Apple provides only first time, need safe it in any storage(for example UserDefaults) for cases if application fail on network request.

Backend

I choose Python as programming language and Flask as Framework for my lightweight backend.

Load private key for working with SignIn with Apple API.

* I used PyJWT 2.0.1 for working with key

Need implement:

  • Method for signin
  • Method for refresh token
  • Method for handle events from Apple

SignIn

First need add method for signin/signin to our’s backend via access code.

Helper method for request to Apple Web API for getting sing info

Example for perform SignIn Web Api method using Flask.

I getting access code from client, then perform request to Apple and decode result

Refresh Token

access_token expiring after some time, so we should provide mechanism for refreshing it.

Helper method for request to Apple Web API for perform refresh token:

Example for perform refresh token Web Api method using Flask.

Refresh token Web Api method

Handle events

User can manage account from General Settings

Manage account in General Settings

Events from Apple to endpoint:

  • email-disabled — disable forwarding
  • email-enabled — enable forwarding
  • consent-revoked — disable account
  • account-delete — removed account

Example for processing events from Apple:

Web Api method for handle events from Apple

More details about events you can read in documentation.

--

--

Dmytro Hrebeniuk 🇺🇦

Mobile Software Engineer, interesting in different things in software development for mobile.