Sign in with apple ios tutorial

Sign in with your Apple ID

Your Apple ID is the account that you use to access all Apple services and make all of your devices work together seamlessly. After you log in, you can use the App Store, iCloud, iMessage, Apple Music, Apple TV+, and more.

Want to use Sign in with Apple on third-party apps or websites? Learn how to use Sign in with Apple.

Sign in on your iPhone, iPad, or iPod touch

Sign in on your Mac

Sign in on your Apple TV

Sign in on apps and other devices

Sign in on your iPhone, iPad, or iPod touch

  1. Open the Settings app.
  2. Tap Sign in to your [device].
  3. Enter your Apple ID and password.
  4. If prompted, enter the six-digit verification code sent to your trusted device or phone number and complete sign in.

If you’re already signed in to iCloud on the iPhone paired with your Apple Watch, you will automatically be signed in to that Apple ID. Learn more about how to set up and sign in to your Apple Watch.

Sign in on your Mac

  1. Choose Apple menu  > System Preferences.
  2. Click Sign In.
  3. Enter your Apple ID and password.
  4. If prompted, enter the six-digit verification code sent to your trusted device or phone number and complete sign in.

Sign in on Apple TV

  1. From the Home screen, choose Settings.
  2. Then choose Users and Accounts and select Add New User…
  3. Select Enter New…, then follow the on screen instructions.

If you use two-factor authentication on an Apple TV (2nd or 3rd generation), you might need to enter a verification code with your password. Learn how to get a verification code on your trusted device or sent to your trusted phone number.

Sign in on apps and other devices

You can use your Apple ID on some third-party devices to sign in to Apple services like Apple Music, the Apple TV app, and more.

Depending on your device, you might need to use an app-specific password.

Sign in to use Apple Music, the Apple TV app, and more on your other devices

You can sign in to Apple Music on Android, or sign in to the Apple TV app on your smart TV or streaming device.

On your Windows PC, you can sign in to iTunes for Windows to buy movies and TV shows, or listen to songs on Apple Music.

Sign in to use iCloud on your other devices

On your Windows PC, you can set up and sign in to iCloud for Windows to access photos, documents, and more.

You can also sign in to iCloud.com from your browser. Learn which iCloud.com features are available on your device.

Читайте также:  Узнать износа аккумулятора айфон

Use Sign in with Apple on third-party apps and websites

If you see a Sign in with Apple button on a participating third-party app or website, you can use your existing Apple ID to quickly set up an account and sign in. Learn how to use Sign in with Apple.

When you sign in to the App Store and other media services for the first time, you might need to add a credit card or other payment information. You can’t sign in to the App Store and other media services with more than one Apple ID at the same time, or update the content you buy with a different Apple ID. Depending on how you created your Apple ID, you might be prompted to upgrade to two-factor authentication on an eligible device.

Learn more

  • To view and manage your Apple ID account details on the web, sign in to appleid.apple.com.
  • Learn more about where you can use your Apple ID.
  • Learn how to manage your subscriptions to services like Apple Music or Apple TV+.
  • If you have multiple Apple IDs, you can’t merge them.

Information about products not manufactured by Apple, or independent websites not controlled or tested by Apple, is provided without recommendation or endorsement. Apple assumes no responsibility with regard to the selection, performance, or use of third-party websites or products. Apple makes no representations regarding third-party website accuracy or reliability. Contact the vendor for additional information.

Источник

How to use Sign in with Apple

Learn how to use Sign in with Apple to create an account for a third-party app or website on your iPhone, iPad, iPod touch, or a web browser.

To use Sign in with Apple, you need to use two-factor authentication and be signed in to iCloud with that Apple ID on your Apple device. Learn more about Sign in with Apple.

Create an account using Sign in with Apple on your iPhone, iPad, iPod touch, or Mac

  1. Tap the Sign in with Apple button on the participating app or website.*
  2. If you’re asked to provide your name and email address, Sign in with Apple automatically fills in the information from your Apple ID. You can edit your name if you like and choose Share My Email or Hide My Email. Learn more about Hide My Email.
  3. Tap Continue and confirm with Face ID, Touch ID, or your device passcode to sign in. If you don’t have Face ID, Touch ID, or a passcode set up, enter your Apple ID password.

Anytime you need to sign in to that app or website, just tap the Sign in with Apple button and complete a simple Face ID, Touch ID, or passcode confirmation. It works the same way on your other Apple devices that you’re signed into with the same Apple ID.

* You need to be signed in with your Apple ID in System Preferences > Apple ID on your Mac or Settings > [your name] on your iPhone, iPad, or iPod touch. You also need two-factor authentication turned on.

Create a Sign in with Apple account on other platforms

You can also use Sign in with Apple on participating apps and websites on the web and on other platforms like Android or Windows.

  1. Tap the Sign in with Apple button on the participating app or website.
  2. When you see a secure, Apple-hosted webpage, enter your Apple ID and password.
  3. The first time you sign in, you’re prompted for a verification code from your trusted Apple device or phone number. Check your device and enter the code. On the web, you can skip this step for 30 days after your initial sign in by choosing to trust the browser you’re currently using.
  4. If you’re asked to provide your name and email address, Sign in with Apple automatically fills in the information from your Apple ID. You can edit your name if you like and choose Share My Email or Hide My Email. Learn more about Hide My Email.
  5. Tap Continue to complete the sign-in process.
Читайте также:  Дисковод для компьютера apple

Upgrade an existing third-party account to Sign in with Apple

Participating third-party apps and websites might give you the option to upgrade an existing account to Sign in with Apple. You can do this through the settings menu of the app or website.

In iOS 14 and iPadOS 14 or later, you might also be given the option to upgrade to Sign in with Apple if you use an easily-guessed, reused, or compromised password with a participating app or website. If you see the prompt, just tap Use Sign in with Apple and follow the onscreen steps. Or, you can upgrade on your iPhone, iPad, or iPod touch:

  1. Go to Settings > Passwords.
  2. Under Security Recommendations, tap an app or website name.*
  3. Tap Use Sign in with Apple, then follow the onscreen steps.

* Only participating apps or websites will be listed.

If you want to use Hide My Email, create a new account with Sign in with Apple. After you convert your account to Sign in with Apple, you can’t change it back.

Источник

Внедряем 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:

Читайте также:  Как пользоваться айфоном 11 pro max

На следующем экране обязательно скачиваем файл с ключом и сохраняем его в безопасном месте, так как после ухода с этого экрана ключ будет недоступен для скачивания. На этой же странице можно увидеть 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.

Источник

Оцените статью