I am currently implementing an authentication function using ASWebAuthenticationSession to log in with my Instagram account.
I set a custom scheme for the callbackURLScheme, but
In the Instagram redirect URL
I was told I can't use a custom scheme.
What should I do with the callbackURLScheme of the ASWebAuthenticationSession in this case?
Authentication Services
RSS for tagImprove the experience of users when they enter credentials to establish their identity using Authentication Services.
Posts under Authentication Services tag
96 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I'm currently implementing a function in SwiftUI to log in with my Instagram account.
It's not working, I'm creating a Firebase Auth function and it comes back to the redirect URL.
This may happen if browser sessionStorage is inaccessible or accidentally cleared. This may happen if browser sessionStorage is inaccessible or accidentally cleared.
I get this error.
I can't implement it. I have tried various methods, but all have failed.
If anyone knows how to do this, please help.
import SwiftUI
import AuthenticationServices
import FirebaseAuth
struct InstagramLoginView: View {
var body: some View {
VStack {
Text("Login with Instagram") // タイトル
Button(action: {
// ボタンが押された時にInstagramのログイン処理を開始
InstagramLoginHelper().startInstagramLogin()
}) {
Text("Login with Instagram")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
}
}
}
class InstagramLoginHelper: NSObject, ASWebAuthenticationPresentationContextProviding {
func startInstagramLogin() {
let clientID = "XXXXXXXXXXXX"
let redirectURI = "https://XXXXXXXXXXX.firebaseapp.com/__/auth/handler"
let authURL = "https://api.instagram.com/oauth/authorize?client_id=\(clientID)&redirect_uri=\(redirectURI)&scope=user_profile,user_media&response_type=code"
let schem = "XXXXXXXXXXXX"
if let url = URL(string: authURL) {
let session = ASWebAuthenticationSession(url: url, callbackURLScheme: schem) { callbackURL, error in
if let error = error {
print("Error during authentication: \(error.localizedDescription)")
return
}
if let callbackURL = callbackURL, let code = URLComponents(string: callbackURL.absoluteString)?.queryItems?.first(where: { $0.name == "code" })?.value {
// 認証コードを使ってFirebaseでログインする
self.loginWithInstagram(authCode: code)
}
}
session.presentationContextProvider = self
session.start()
}
}
func loginWithInstagram(authCode: String) {
// Firebaseのauthインスタンスを取得
let auth = Auth.auth()
// InstagramのOAuthプロバイダを使用する
let provider = OAuthProvider(providerID: "instagram.com")
// Instagramの認証コードを使って、プロバイダの認証資格情報を生成
provider.getCredentialWith(nil) { credential, error in
if let error = error {
print("Error during authentication: \(error.localizedDescription)")
return
}
if let credential = credential {
// Firebaseにログイン
auth.signIn(with: credential) { authResult, error in
if let error = error {
print("Error during Firebase authentication: \(error.localizedDescription)")
} else {
print("Successfully authenticated with Firebase.")
}
}
}
}
}
// ASWebAuthenticationPresentationContextProvidingの実装
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return UIApplication.shared.windows.first { $0.isKeyWindow } ?? ASPresentationAnchor()
}
}
#Preview {
InstagramLoginView()
}
I am currently using the ability to log in with my Instagram account using ASWebAuthenticationSession and it is not working!
I filled in the URL directly and there was no problem on the web, but when I run it in SwiftUI in Xcode, it doesn't work and
Error: The operation couldn’t be completed. (com.apple.AuthenticationServices.WebAuthenticationSession error 2.)
I get this error.
I was told that I need a custom scheme to return to mobile, but the Instagram redirect URL says no custom scheme.
What should I do?
IDs and URLs are placed under assumption.
I have no idea since this is my first implementation.
Should I send the scheme URL from the website to mobile once using Django or something else?
import SwiftUI
import AuthenticationServices
struct InstagramLoginView: View {
@State private var authSession: ASWebAuthenticationSession?
@State private var token: String = ""
@State private var showAlert: Bool = false
@State private var alertMessage: String = ""
var body: some View {
VStack {
Text("Instagram Login")
.font(.largeTitle)
.padding()
Button(action: {
startInstagramLogin()
}) {
Text("Login with Instagram")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
if !token.isEmpty {
Text("Token: \(token)")
.padding()
}
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Error"), message: Text(alertMessage), dismissButton: .default(Text("OK")))
}
}
func startInstagramLogin() {
let clientID = "XXXXXXXXXX" // Instagram client ID
let redirectURI = "https://example.com" // Instagram Redirect URI
guard let authURL = URL(string: "https://api.instagram.com/oauth/authorize?client_id=\(clientID)&redirect_uri=\(redirectURI)&scope=user_profile,user_media&response_type=code") else {
print("Invalid URL")
return
}
authSession = ASWebAuthenticationSession(url: authURL, callbackURLScheme: "customscheme") { callbackURL, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let callbackURL = callbackURL else {
print("Invalid callback URL")
return
}
if let code = URLComponents(string: callbackURL.absoluteString)?.queryItems?.first(where: { $0.name == "code" })?.value {
print("Authorization code: \(code)")
getInstagramAccessToken(authCode: code)
}
}
authSession?.start()
}
func getInstagramAccessToken(authCode: String) {
let tokenURL = "https://api.instagram.com/oauth/access_token"
var request = URLRequest(url: URL(string: tokenURL)!)
request.httpMethod = "POST"
let clientID = "XXXXXXXXXXXX"
let clientSecret = "XXXXXXXXXXXXXX" // Instagram clientSecret
let redirectURI = "https://example.com/"
let params = "client_id=\(clientID)&client_secret=\(clientSecret)&grant_type=authorization_code&redirect_uri=\(redirectURI)&code=\(authCode)"
request.httpBody = params.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let data = data else {
print("No data")
return
}
if let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let accessToken = jsonResponse["access_token"] as? String {
print("Access Token: \(accessToken)")
// ここでアクセストークンを使用してInstagram APIにアクセスする
} else {
print("Failed to get access token")
}
}.resume()
}
}
#Preview {
InstagramLoginView()
}
Hi, I'm leveraging ASAuthorizationSecurityKeyPublicKeyCredentialProvider to authenticate users to an internal service using security keys or passkeys. I'm not using Sign in with Apple - registration is done in another internal service. We're using associated domains. This is on MacOS only.
I'm wondering whether I can programatically determine whether the user has a passkey enrolled with our super-secret-internal-service.com domain already?
The reason I'm asking is simply better UX - if the user doesn't have a passkey enrolled, I'd like to avoid offering them an option to use a platform authenticator and only offer them to tap their security key. We can assume that all users already have their security keys enrolled already.
So something like the following:
let securityKeyProvider = ASAuthorizationSecurityKeyPublicKeyCredentialProvider(relyingPartyIdentifier: options.rpId)
let securityKeyRequest = securityKeyProvider.createCredentialAssertionRequest(challenge: options.challenge.data(using: .utf8) ?? Data())
let platformProvider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: options.rpId)
let platformKeyRequest = platformProvider.createCredentialAssertionRequest(challenge: options.challenge.data(using: .utf8) ?? Data())
var authRequests: [ASAuthorizationRequest] = [securityKeyRequest]
if (userHasPasskeyForDomain("super-secret-internal-service.com")) { // TODO how do I check this??
authRequests.append(platformKeyRequest)
}
let authController = ASAuthorizationController(authorizationRequests: [platformKeyRequest, securityKeyRequest])
Many thanks!
Hello everyone,
I’m encountering an issue with Sign in with Apple in my watchOS app and would appreciate any guidance.
Background:
Initially, I did not have the Sign in with Apple capability enabled on my watchOS app.
I have since enabled the capability and grouped it with my iOS app.
For new user accounts created after this change, everything works perfectly:
The credentialState check returns .authorized on both iOS and watchOS.
However, for existing user accounts (created before enabling the capability on watchOS):
The credentialState check returns not authorized on watchOS.
The check still returns .authorized on iOS for these accounts.
Error Details:
When calling ASAuthorizationAppleIDProvider.credentialState(forUserID:) on watchOS for existing accounts, I receive the following error:
Error Domain=AKAuthenticationError Code=-7074 "(null)"
My Suspicions:
I believe the issue arises because the existing Sign in with Apple tokens are only associated with the iOS app’s bundle identifier and not with the watchOS app’s bundle identifier. Since the capability wasn’t enabled on the watchOS app when these accounts were created, their tokens aren’t valid for the watchOS app.
Questions:
Is this the correct explanation for why the credentialState check fails on watchOS for existing accounts, resulting in the AKAuthenticationError Code=-7074 error?
Can I update or migrate the existing accounts so that their Sign in with Apple tokens are valid for the watchOS app as well? If so, how can this be achieved?
Are there any best practices for handling this situation without requiring users to re-authenticate or removing the credentialState check from the watchOS app?
Goal:
I want to maintain the credentialState check on the watchOS app because it works correctly for new accounts and is important for security. I’m looking for a solution that allows existing users to continue using the app on their Apple Watch without interruption or additional sign-in steps.
Any help or suggestions would be greatly appreciated!
Thank you!
I am trying to implement a login page in SwiftUI for an idp that relies on passkeys only, following the sample code from the food truck app.
The registration of a new passkey works fine but when it comes to signing in, ASAuthorizationPlatformPublicKeyCredentialProvider().createCredentialAssertionRequest returns a signature that cannot be verified by the server.
On safari (and other browsers) the signing in&up process works fine and additionally, a passkey registered from the swift app works on the web, which leads me to believe there is an issue in the AuthenticationServices framework as every other steps works without any problem.
The verification of the signature happens on the server side (after several validation steps of the other parameters) with WebCrypto.subtle.verify(verifyAlgorithm, key, signature, data);
With the data argument being a concat of the clientDataJSON and the authenticatorData and for an apple authenticator, the key argument (which is the public key stored by the server) is an EC2 key with the following verifyAlgorithm argument:
verifyAlgorithm = {
name: 'ECDSA',
hash: { name: SHA-256 },
};
After carefully analyzing multiple responses, coming both from the app and safari, either on iOS or macOS, I can safely say that the ASAuthorizationResult.passkeyAssertion returns the expected values for:
rawAuthenticatorData
rawClientDataJSON
credentialID
userID
Which all match the expected values during the server-side validation. The only remaining value from the ASAuthorizationResult.passkeyAssertion is the signature, which as mentioned above, is invalid when verified by the server.
I already submitted a bug report (FB15113372) as well as a DTS request, but haven’t received any feedback yet.
In order to further narrow down the problem, I replicated the signature verification process in a sage notebook. I got the same result: the signature produced in Safari is fine, but the one from the Swift app is invalid. I collected some thoughts of potential issues in this notebook, but I still haven’t been able to draw a clear conclusion on why does this issue occur.
Hence if anyone has knowledge of this issue or has a similar problem with signature verification, their advice is most welcomed.
Thank you in advance for your help
PS: All the recent tests were made on the latest publicly available OS releases (iOS 18.01, macOS 15.0.1) and Xcode 16.0
The peripheral is initiating a passkey entry mechanism, IOS device is getting a pop up to enter the passkey but the WatchOS device is not displaying any pop-up.
Is there anything to be enabled from the watch side?
I want to publish an unlisted app for an enterprise audience and would like to know if the registration flow is required.
Since my app will only have features that require log in Apple guidelines say it needs the registration process but to ensure that only desired users will have access I plan to create accounts from outside the app, thus making the registration within the app unnecessary.
Is there any docs, guideline or policy that states that registration is not needed for unlisted apps?
When tapping on "password" in the accessory view above the keyboard, no password manger is opened. The keyboard just closes and re-opens.
I have made sure a password exists and is available to be used.
I have replicated this within my own app, but also from within the Settings app on the simulator (see attached gif) so I am confident it is not a coding issue on my side.
I have replicated it on both iOS 17 and iOS 18
I am using Xcode Version 16.0 (16A242d)
I am running macOS Sonoma Version 14.7 (23H124)
I am fairly confident I have not experienced this when working on another clients app. I was using Xcode 15 for that so not sure if this is something introduced with Xcode 16.
when I performAutoFillAssistedRequests ,my keyboard cannot show passkeys that could choose,and nothing callback.i don't know the error reason.but I could request successfully by authController.performRequests.
We are using performRequestsWithOptions to enable passkey on ios app.
[authController performRequestsWithOptions:ASAuthorizationControllerRequestOptionPreferImmediatelyAvailableCredentials];
Based on apple doc, this will "Tells the authorization controller to prefer credentials that are immediately available on the local device.", and fail silently if there are no credentials available.
However, in recent testing, we identified that on one device, we are seeing QR code popping up even though there's no credential on the device. Question
is this a bug on the OS system?
If this is a bug, what are the causes that will trigger this condition?
Is there a recommendation to mitigate the issue? Should we move to the new api?
Thank you.
My device has open passkeys , in setting app. when I performAutoFillAssistedRequests,callback performRequests ASAuthorizationError(rawValue: 1001)".at same time,authController.performRequests could request successfully
Hi everyone, I am trying to implement 'Sign-in with Apple' to my website using nextauth verion 4.24.5 on next.js version 14.2.7. I set up the Apple ID and generated the Apple secret. The Apple ID is set to the service ID. Whenever I try and sign in on the site using Apple, (after submitting my username and password on the redirected appleid.com page), nextauth returns this error:
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error id_token not present in TokenSet {
error: TypeError: id_token not present in TokenSet
{
name: 'OAuthCallbackError',
code: undefined
},
providerId: 'apple',
message: 'id_token not present in TokenSet'
}
This occurs even after specifying openid in the scope, setting the checks to pkce, setting the checks to state, setting idToken to true, and other changes to the config. I have used the AppleProvider from nextauth and my own custom provider and got the same result. The nextauth GoogleProvider works just fine so I know nextauth is set up properly. Do you know how I can fix this?
my apple nextauth apple provider config:
const customAppleProvider = {
id: "apple",
name: "Apple",
type: "oauth",
wellKnown: "https://appleid.apple.com/.well-known/openid-configuration",
authorization: {
params: {
scope: "name email openid",
response_mode: "form_post"
},
},
state: true,
checks: ["pkce"],
idToken: true,
clientId: process.env.APPLE_ID,
clientSecret: process.env.APPLE_SECRET,
profile(profile) {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: null,
}
},
};
We have some third-party SDKs do not support arm64 simulator, so we excluded arm64 for Any iOS Simulator SDK in Excluded Architectures. But in this case, ASWebAuthenticationSession will display abnormally.
We submitted FB14853757 during the beta period, but have not received any response. This issue still exists in the official version. I hope it can be resolved. Thank you!
I'm working on Authenticating a User Through a Web Service and using https callback.
When running the project on real device all works as expected, but when I run the same project with the same config on simulator I get this error:
Login failed: Error Domain=com.apple.AuthenticationServices.WebAuthenticationSession Code=1 "Application with identifier bundle_id is not associated with domain my_domain. Using HTTPS callbacks requires Associated Domains using the webcredentials service type for my_domain." UserInfo={NSLocalizedFailureReason=Application with identifier bundle_id is not associated with domain my_domain. Using HTTPS callbacks requires Associated Domains using the webcredentials service type for my_domain.}
Xcode 15.4
iOS 17.5
@available(iOS 17.4, *)
public init(url URL: URL, callback: ASWebAuthenticationSession.Callback, completionHandler: @escaping ASWebAuthenticationSession.CompletionHandler)
Working on a file server in c/c++ and need to do following:
Validate user credentials (mac Username & password)
Impersonate user security context in a thread running in a daemon, so that I can enumerate user's home directory and files/folders.
Regarding 2, found API: pthread_setugid_np - is this the right approach? If so, how do I verify user credentials and call this API?
Found this section in TN2083:
Does this mean that its really not possible to impersonate user and access their home directory etc if the user isn't logged in via terminal/console? or if they have FileVault enabled?
In AuthorizationServices support for displayName exists in:
class ASAuthorizationSecurityKeyPublicKeyCredentialProvider func createCredentialRegistrationRequest( challenge: Data, displayName: String, name: String, userID: Data ) -> ASAuthorizationSecurityKeyPublicKeyCredentialRegistrationRequest
but is not supported in the corresponding class:
class ASAuthorizationPlatformPublicKeyCredentialProvider func createCredentialRegistrationRequest( challenge: Data, name: String, userID: Data ) -> ASAuthorizationPlatformPublicKeyCredentialRegistrationRequest
I was under the impression that this should be supported in public key credential registration?
I'm using the same code to authenticate using passkeys on iOS and macOS. On iOS (simulator, on-device, and deployed with TestFlight), I have no issues registering or authenticating with a passkey. On macOS using Catalyst, when I attempt to authenticate with a passkey (ASAuthorizationController#performRequests), I see the following error:
Error Domain=com.apple.AuthenticationServices.AuthorizationError Code=1004 "Application with identifier TEAMID.com.bundle is not associated with domain bundle.com" UserInfo={NSLocalizedFailureReason=Application with identifier TEAMID.com.bundle is not associated with domain bundle.com}
I've double-checked my apple-app-site-association file is being served from the associated domain, and I've double-checked that the Apple CDN is also returning that same association file with webcredentials for my team/bundle.
Any ideas why it would succeed in iOS environments but fail under macOS with Catalyst?
We use ASWebAuthenticationSession in our app to perform SAML auth on iOS devices. It works fine with Safari. However, if we config other browsers, such as Chrome, as a default browser on iOS device, ASWebAuthenticationSession still load Safari in embedded window and auth cookies is only stored in Safari. Can ASWebAuthenticationSession work with default browser on iOS similar as it works on MacOS?
Thanks,
Ying
Similar to this thread. How do we go about testing or triggering the UI for this new iOS/macOS 18 API?
https://developer.apple.com/documentation/authenticationservices/ascredentialproviderviewcontroller/prepareinterfaceforuserchoosingtexttoinsert()
Thanks!