- Make signing in easy.
- Planning
- Examples of Use Cases
- Guidelines
- Implementing
- Service ID and Key Configuration
- Email Relay Service
- Unity Tools
- Web and Other Platforms
- Service API
- Testing and Verifying
- Xcode
- Resources
- Внедряем Sign in with Apple — систему авторизации от Apple
- Настраиваем Apple Developer Account
- Добавляем кнопку Sign In with Apple в iOS-приложение
- Реализуем Sign in with Apple для web и Android
- Получение данных
- Implementing Sign in with Apple on the server-side
- Feature Summary
- 0 ) Prerequisites
- 1 ) Generate the Identity Token:
Make signing in easy.
Provide a fast, secure, and privacy-friendly way for users to set up an account and start using your apps and websites.
Planning
Sign in with Apple allows you to set up a user account in your system, complete with name, verified email address, and unique stable identifiers that allow the user to sign in to your app with their Apple ID. It works on iOS, macOS, tvOS, and watchOS. You can also add Sign in with Apple to your website or versions of your app running on other platforms. Once a user sets up their account, they can sign in anywhere you deploy your app.
Examples of Use Cases
With Sign in with Apple, it’s easy to:
- Allow users to create an account early in your app experience if your app has limited functionality without an account.
- Allow users to create an account after interacting with features of your app. For example, to save progress or set up a profile.
- Allow users to create an account after completing a purchase as a guest.
- Allow users with existing accounts to sign in or reauthenticate to any version of your app or website.
Guidelines
Apps that use a third-party or social login service to set up or authenticate the user’s primary account with the app must also offer Sign in with Apple as an equivalent option. As you plan and design your app or website for Sign in with Apple, make sure to follow these guidelines. In addition, the Human Interface Guidelines include downloadable left-aligned, center-aligned, and logo-only buttons. App updates must follow these guidelines starting June 30, 2020.
Implementing
Service ID and Key Configuration
You’ll need to use Certificates, Identifiers & Profiles to set up identifiers and keys in your Apple Developer account before you can implement Sign in with Apple. Organizations can register up to 100 website URLs for each Service ID enabled for Sign in with Apple. Individuals can register up to 10.
Email Relay Service
Apple’s private email relay service is used by privacy-conscious users that keep their personal email address private when setting up an account. In order to send email messages through the relay service to these users, you will need to register your outbound email domains, subdomains, or email addresses. The registration process provides informational Sender Policy Framework record checks and does not require website server file verification. Organizations can register up to 100 outbound email sources. Individuals can register up to 32.
If we detect that emails sent from your account were unable to be delivered by Apple’s private email relay service, we’ll send periodic email notifications to Account Holders and admins. Account Holders and admins can turn off these email notifications in the More section of Certificates, Identifiers & Profiles.
Use the AuthenticationServices framework to let users set up accounts and sign in to your native iOS, macOS, tvOS, and watchOS apps.
Unity Tools
Easily integrate Sign in with Apple into games and apps built with Unity using a new Unity Asset Store package.
Web and Other Platforms
Use Sign in with Apple JS to let users set up accounts and sign in to your website and apps on other platforms.
Service API
Use the Sign in with Apple API to validate the authorization code provided to your app and check a user’s status directly with Apple servers.
Testing and Verifying
Xcode
To test your apps, use the latest version of Xcode and update your devices to the latest versions of iOS, iPadOS, macOS, and tvOS. To test your website, you’ll need to group it with an app that is enabled for Sign in with Apple and is available on the App Store.
Resources
Find tools, documentation, and resources you need to implement Sign in with Apple.
Источник
Внедряем Sign in with Apple — систему авторизации от Apple
Этим летом на конференции WWDC 2019 Apple представила собственную систему авторизации Sign in with Apple и сделала ее обязательной для всех приложений в App Store, которые используют вход через соцсети. Исключение составляют образовательные, корпоративные, правительственные и бизнес-приложения, использующие собственную авторизацию. К Sign in with Apple Apple сделала качественную документацию, и в этой статье мы на примере ЦИАН расскажем, как внедрить ее в свой сервис.
Настраиваем Apple Developer Account
Работа по интеграции начинается с настройки аккаунта разработчика. Сначала нужно включить опцию Sign In with Apple для вашего App ID. Для этого заходим в список идентификаторов в Apple Developer Account, выбираем необходимый App ID и включаем для него опцию Sign In with Apple.
Теперь настраиваем Service ID — уникальный идентификатор web-приложения, который понадобится для обращения к Sign in with Apple API. Всего на один App ID можно создать до 5 Service ID. Для этого нажимаем кнопку создания идентификаторов, выбираем Service ID, заполняем необходимые поля и нажимаем Edit в поле Sign In With Apple. Откроется форма, где выбираем правильный Primary App ID, указываем веб-домен и перечислям URL для редиректа после успешного логина. Надо учитывать, что можно ввести только 10 Return URLs:
Для сохранения нажимаем Save, Continue и Register. Да, при любых изменениях конфигурации необходимо нажимать все три кнопки, иначе изменения не вступят в силу.
Теперь в списке Service ID выбираем созданный идентификатор и опять нажимаем Edit в поле Sign In With Apple. В открывшемся окне у поля с веб-адресом видим две новые кнопки:
Этот файл необходим, чтобы Apple верифицировала ваш ресурс. Скачиваем его и размещаем его на своем ресурсе. Сразу у нас этот финт не сработал: когда наши админы добавили файл, то по указанному url срабатывал редирект (302) на файл, лежащий в другом месте, и Apple его не верифицировал. Тогда пришлось размещать файл по прямому доступу по URL (200). После того как Apple успешно проверит файл, рядом с доменом загорится зеленая галочка:
Из раздела идентификаторов переходим в раздел Keys и создаем новый ключ. Для этого ставим галочку Sign In with Apple и нажимаем сначала Configure, чтобы проверить App ID, затем Continue:
На следующем экране обязательно скачиваем файл с ключом и сохраняем его в безопасном месте, так как после ухода с этого экрана ключ будет недоступен для скачивания. На этой же странице можно увидеть Key ID, который нам еще понадобится:
Для пользователей у Sign In with Apple есть бонус: она позволяет предоставить фейковый e-mail, на который можно писать только с доверенных адресов. В этом случае нужна дополнительная настройка. Открываем раздел More, нажимаем Configure в разделе Sign In with Apple и вписываем свой URL:
Добавляем кнопку Sign In with Apple в iOS-приложение
ЦИАН работает на трех платформах: iOS, Android, Web. Для iOS есть нативное SDK, поэтому авторизация будет выглядеть следующим образом:
Чтобы добавить в iOS-приложение Sign in with Apple, добавляем кнопку ASAuthorizationAppleIDButton и вешаем на нее обработчик нажатия:
Кроме ASAuthorizationAppleIDProvider, обратите внимание еще на ASAuthorizationPasswordProvider, который позволяет получать связки «логин-пароль» из Keychain.
Теперь мы реализуем ASAuthorizationControllerPresentationContextProviding:
Создаем делегат ASAuthorizationControllerDelegate, который сообщает об успехе или ошибке:
Полученный authorizationCode мы отправляем на сервер и ждем ответа от бэкенда об успешности авторизации в нашей системе.
Реализуем Sign in with Apple для web и Android
Внезапно, для Android и Web Apple не предоставляет SDK, поэтому в обоих случаях нужно открыть страницу авторизации от Apple и процесс будет иным:
URL для страницы авторизации выглядит следующим образом:
Рассмотрим его параметры:
- client_id — Service ID, который регистрировали выше.
- redirect_uri — URI, куда пользователь перенаправляется после успешной аутентификации через AppleID. Этот URI мы указывали выше при настройке Apple Developer.
- state — идентификатор сессии пользователя, который Apple вернет при вызове redirect_uri, чтобы мы могли проверить отправителя. Правило генерации этого параметра можете придумать самостоятельно, например, рандомную строку.
- scope — в этом параметре указывается, какая нужна информация от пользователя. Например, name, email или сразу оба, как в примере выше.
- response_type — этот параметр указывает, в каком виде нужен ответ. Он может быть code или id_token. Если выбрать id_token, то его нужно уточнить параметром response_mode, в котором можно указать query, fragment и form_post.
После успешной двухфакторной аутентификации через appleID Apple вызовет указанный redirect_uri и передаст параметры state и code:
В параметре code передается одноразовый код аутентификации пользователя, который действует в течение 5 минут. В параметре state — идентификатор сессии, отправленный при создании формы авторизации, а в параметре user — данные пользователя.
Получение данных
На всех клиентах, чтобы сохранить данные пользователя, нужно получить от Apple access_token. Для этого сначала запрашиваем authorization_code:
- в client_id указывается созданный для web-приложений ServiceID и AppID для iOS-приложения.
- code — мы получили выше после редиректа или передали с iOS-клиента
- в параметре grant_type передаем цель получения токена: авторизация (authorization_code) или продление токена (refresh_token)
- в параметре client_secret — JSON Web Tokens на основе секретного ключа, полученного при регистрации приложения.
Создать JSON Web Tokens можно на Python:
Если все прошло успешно, то в ответе придут такие параметры:
Ура, вот и access_token. Вместе с ним приходит refresh_token, которым можно обновить при необходимости access_token.
Информация о пользователе хранится в поле id_token, но его нужно декодировать:
Apple_public_key — это публичный ключ, который можно получить по ссылке.
После декодирования получаем:
Email передается только один раз, когда пользователь впервые авторизуется в вашем сервисе через Sign in with Apple. В следующий раз Apple передаст эти данные только в том случае, если пользователь самостоятельно отвяжет ваше приложение. Этим авторизация от Apple отличается от других сервисов, где данные можно получить через API, и мы не нашли информацию о том, что они планируют реализовать что-то подобное.
В этом ответе нам нужны параметры sub, который передается каждый раз, и email, поэтому мы сохраняем их у себя в системе и сообщаем клиенту о успешной авторизации. PROFIT.
Источник
Implementing Sign in with Apple on the server-side
With the new iOS 13 release, developers gained another way to implement authentication. At WWDC 2019, Apple announced the “Sign In with Apple” feature, introducing a new identity provider based on Apple IDs that can be used on mobile and web apps. Integrating with this feature is going to be mandatory for all apps that use third-party libraries for authenticating users (such as using Facebook or Google login features). Since it is a new feature, information about it is not easy to find. We implemented this feature here at Playkids and based on the knowledge we acquired on the process, we want to share with you what we learned so you can implement it too.
Sign in with Apple works natively on iOS, macOS, tvOS, and watchOS. And it works in any browser, which means you can deploy it on your website and in versions of your apps running on other platforms.
Feature Summary
The main goal of an authentication feature is to enable the validation of users through different app flows. On “Sign in With Apple”, authentication relies on the generation and validation of an identity token. The 3 operations that manage this identity token are the following:
- 1) Generate Identity token: After the users click on the sign-in button, a code is created. This code should be passed alongside some apple developer account parameters and alongside a generated client secret to an Apple API, through an HTTP Post request. This operation returns an Apple identity token that will be used to verify a user’s identity.
- 2) Refresh Identity token: Receives an identity token and extends its lifetime by making an HTTP Post request to an Apple API. This operation returns a new Apple identity token.
- 3) Validate Identity token: Validate if an identity token is valid using a public key fetched from Apple.
We see two different approaches that can be followed to add the “Sign In With Apple” flow to your app:
A) Full server-side: Your backend server will perform all three operations, managing the entire lifecycle of the identity tokens. The apps will only be responsible for sending the generated code after the user clicks on the sign-in button.
B) App + server : The apps will be responsible for generating and refreshing the identity tokens, while your backend server will be responsible only for validating them.
We chose to implement the approach B for PlayKids App. We decided that because we already integrate with different identity providers and because we already manage authentication tokens generated by ourselves. On our implementation, the app became responsible for generating the identity token and passing it to our backend. After our backend successfully validates the Apple identity token, we generate a new authentication token of our own and return it to the app. From this point forward, the app will handle authentication in a generic way.
Let’s go through the implementation details now:
0 ) Prerequisites
For sure, you will need an Apple Developer Account to obtain the necessary parameters, like your app identifier.
At your identifier, you will need to edit configurations and enable the Sign in with Apple feature. There you will able to configure the feature to use your app as a primary app or to use it as part of an app group, and you will also be able to see the Grouped App IDs
With this option enabled, the next step will be to prepare the parameters needed to perform a post request to the Apple API.
1 ) Generate the Identity Token:
This is the call to generate an Apple Identity Token (See the class below). If this call is successful, it means that the user was validated on the Apple side and that it can use the returned identity token to behave as a logged Apple user. To perform this request, you will need to do some configuration steps, like obtaining your client id (In the image below the client id is com.my.identifier) and generating your client secret.
The full request properties can be found in generate and validate tokens.
The validation server returns a TokenResponse object on successful validation. When using this endpoint for authorizing the user, use the following parameters: client_id , client_secret , grant_type , code , and redirect_uri . When using this endpoint for validating the refresh token, use the following parameters: client_id , client_secret , grant_type , and refresh_token.
The response of this API is the Apple identity token. It is the same token as the one returned on the app flow if you decide to follow approach B. With this token you have the necessary information to validate that your user was authenticated by Apple.
You can see the error responses on Error response API documentation.
At first, you will need a client secret, which is nothing more than a token that you must create and sign and you can see the implementation in the code below. ( sign the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm).
If you want to use the sign in with apple in your web app, you will also need to configure a confirmed domain to redirect after authenticating in Apple. Basically, you will need to configure a service id, linked to your App identifier mentioned early.
Services IDs: For each website that uses Sign In with Apple, register a services identifier (Services ID), configure your domain and return URL, and create an associated private key.
Источник