Balbas Code

AppleのOAuth認証で使用するuseridを取得する

公開日: 2024-11-01 12:53:29

本日はAppleのOAuth認証を使用する際の流れをまとめていきます。
前回の記事と合わせて、実際に認証機能(データ引き継ぎ)を実装したところ、iOSのみのアプリであればこちらのAppleの認証機能を実装すれば事足りる感じがしました。


理由としてGoogle認証の場合下記の画面が表示されてしまいます。
apple_oauth
得体の知らないアプリにこちらのような赤枠のような文言が表示されるのは不安でしかないです。
実際はログインが完了したらGoogleが発行するuserid(数字のみの値)を取得するだけでも、
・あなたの名前
・メールアドレス
・言語設定
・プロフィール写真
こちらが取得されます。と表示されてしまいます。


しかし、Appleで認証を行う場合、iPhone端末にログインした状態で使っているので特にこちらのような画面やUserID,Passwordの入力画面も出ずに進めることができました。

こちらについてもGoogle認証と同様にAppleDeveloper内で初期設定をする必要があるのでまとめていきます。





AppleDeveloper
apple_oauth
対象のアプリを選択


apple_oauth
Appleでサインインを選択
※編集ボタンの内容はWebで認証を行う場合などは記載する必要があるようですが、iOSアプリのみで使用する場合は編集不要です。


これでAppleDeveloperの設定は終了です。
次はXcodeに設定を反映させます。

Xcode
Target→「Signing & Capabilities」→「+ Capability」→「Sign in with Apple」
apple_oauth

apple_oauth
こちらが追加されればOKです。


あとはSwift側のコードです。


import AuthenticationServices  // Appleのサインイン用
import JWTDecode

// Appleサインイン処理
private func startAppleSignIn() {
let provider = ASAuthorizationAppleIDProvider()
let request = provider.createRequest()
request.requestedScopes = [.fullName, .email]

let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}


認証成功時


// Appleサインインの結果処理
extension DataTransferView: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {

// 認証成功時
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential,
let identityTokenData = appleIDCredential.identityToken,
let tokenString = String(data: identityTokenData, encoding: .utf8) {
handleToken(tokenString)
}
}

// 認証失敗時
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print("Appleサインインエラー: \(error)")
}

func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
}


トークンのデコードと検証


    // トークンを処理する共通メソッド
func handleToken(_ token: String) {
do {
let jwt = try decode(jwt: token)

// ユーザー名、メールアドレス、一意の識別子の取得
let userId = jwt.claim(name: "sub").string ?? "不明"
print("ユーザーID: \(userId)")

// 有効期限(exp)を確認
if let expirationDate = jwt.expiresAt {
if expirationDate > Date() {
print("トークンは有効です。")
} else {
print("トークンの有効期限が切れています。")
}
} else {
print("有効期限がトークンに含まれていません。")
}

} catch {
print("トークンのデコードに失敗しました: \(error)")
}
}



実行結果
apple_oauthapple_oauth

後はこちらの値はAppleが発行したユーザーIDに対する一意の値になるので、こちらを使ってUserテーブルに紐づければ新機種や複数の端末で同時に使用できるようになります。