Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions FirebaseAuth/Sources/Swift/Auth/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2341,6 +2341,29 @@ extension Auth: AuthInterop {
}
#endif

// MARK: IDP Initiated SAML Sign In

public func signInWithSamlIdp(ProviderId providerId: String,
SpAcsUrl spAcsUrl: String,
SamlResp samlResp: String) async throws -> AuthDataResult {
let samlRespBody = "SAMLResponse=\(samlResp)&providerId=\(providerId)"
let request = SignInWithSamlIdpRequest(
requestUri: spAcsUrl,
postBody: samlRespBody,
returnSecureToken: true,
requestConfiguration: requestConfiguration
)
let response = try await backend.call(with: request)
let user = try await completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: response.expirationDate,
refreshToken: response.refreshToken,
anonymous: false
)
try await updateCurrentUser(user)
return AuthDataResult(withUser: user, additionalUserInfo: nil)
}

// MARK: Internal properties

/// Allow tests to swap in an alternate mainBundle, including ObjC unit tests via CocoaPods.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Foundation

final class SignInWithSamlIdpRequest: AuthRPCRequest {
typealias Response = SignInWithSamlIdpResponse
private let config: AuthRequestConfiguration
private let requestUri: String
private let postBody: String
private let returnSecureToken: Bool

init(requestUri: String,
postBody: String,
returnSecureToken: Bool,
requestConfiguration: AuthRequestConfiguration) {
self.requestUri = requestUri
self.postBody = postBody
self.returnSecureToken = returnSecureToken
config = requestConfiguration
}

func requestConfiguration() -> AuthRequestConfiguration {
return config
}

func requestURL() -> URL {
var comps = URLComponents()
comps.scheme = "https"
comps.host = "identitytoolkit.googleapis.com"
comps.path = "/v1/accounts:signInWithIdp"
comps.queryItems = [URLQueryItem(name: "key", value: config.apiKey)]
return comps.url!
}

var unencodedHTTPRequestBody: [String: AnyHashable]? {
let body: [String: AnyHashable] = [
"requestUri": requestUri,
"postBody": postBody,
"returnSecureToken": returnSecureToken,
]
return body
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Foundation

struct SignInWithSamlIdpResponse: AuthRPCResponse {
/// The user raw access token.
let idToken: String
/// Refresh token for the authenticated user.
let refreshToken: String
/// The provider Identifier
let providerId: String
/// The email id of user
let email: String
/// The calculated date and time when the token expires.
let expirationDate: Date

init(dictionary: [String: AnyHashable]) throws {
guard
let email = dictionary["email"] as? String,
let expiration = dictionary["expiresIn"] as? String,
let idToken = dictionary["idToken"] as? String,
let providerId = dictionary["providerId"] as? String,
let refreshToken = dictionary["refreshToken"] as? String
else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
self.idToken = idToken
self.refreshToken = refreshToken
self.providerId = providerId
self.email = email
let expiresInSec = TimeInterval(expiration)
expirationDate = Date().addingTimeInterval(expiresInSec ?? 3600)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,64 @@

// Implementing this delegate method is needed when swizzling is disabled.
// Without it, reCAPTCHA's login view controller will not dismiss.
// Without it, IdP Initiated SAML Sign In will not work.
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
let url = urlContext.url
_ = Auth.auth().canHandle(url)
/// Handle IdP Initiated SAML deep link myapp://saml?resp=<samlResponse>
if url.scheme?.lowercased() == "myapp", /// replace with your custom scheme
url.host?.lowercased() == "saml" { /// replace with your host
let spAcsUrl =

Check warning on line 61 in FirebaseAuth/Tests/SampleSwift/AuthenticationExample/SceneDelegate.swift

View workflow job for this annotation

GitHub Actions / integration-tests (SwiftApiTests)

initialization of immutable value 'spAcsUrl' was never used; consider replacing with assignment to '_' or removing it

Check warning on line 61 in FirebaseAuth/Tests/SampleSwift/AuthenticationExample/SceneDelegate.swift

View workflow job for this annotation

GitHub Actions / integration-tests (ObjCApiTests)

initialization of immutable value 'spAcsUrl' was never used; consider replacing with assignment to '_' or removing it

Check warning on line 61 in FirebaseAuth/Tests/SampleSwift/AuthenticationExample/SceneDelegate.swift

View workflow job for this annotation

GitHub Actions / integration-tests (AuthenticationExampleUITests)

initialization of immutable value 'spAcsUrl' was never used; consider replacing with assignment to '_' or removing it
"https://iostemp-8a944.web.app/googleidp-saml/acs" /// replace with your SP ACS URL
if let rawQuery = url.query {
var respValue: String?
for pair in rawQuery.split(separator: "&", omittingEmptySubsequences: false) {
let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
if parts.count == 2, parts[0] == "resp" {
respValue = String(parts[1])
break
}
}
if let resp = respValue {
let alert = UIAlertController(
title: "SAML Sign In",
message: "Enter Provider ID",
preferredStyle: .alert
)
alert.addTextField { tf in
tf.placeholder = "Provider ID"
tf.text = "saml.provider"
tf.autocapitalizationType = .none
tf.autocorrectionType = .no
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in
let providerId = alert.textFields?.first?.text?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
let requestUri = alert.textFields?.last?.text?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
guard !providerId.isEmpty, !requestUri.isEmpty else { return }
Task {
do {
_ = try await AppManager.shared.auth().signInWithSamlIdp(
ProviderId: providerId,
SpAcsUrl: requestUri,
SamlResp: resp
)
} catch {
print("IdP-initiated SAML sign-in failed with error:", error)
}
}
})
var top = window?.rootViewController
while let presented = top?.presentedViewController {
top = presented
}
top?.present(alert, animated: true)
}
}
}
}

// URL not auth related; it should be handled separately.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#if os(iOS)

@testable import FirebaseAuth
import XCTest

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
class SignInWithSamlIdpTests: TestsBase {
func testSignInWithSamlFailureInvalidProvider() async throws {
try? await deleteCurrentUserAsync()
let invalidProvider = "saml.invalid"
let spAcsUrl = "https://example.com/saml-acs"
let samlResp = "samlResp"
do {
_ = try await Auth.auth().signInWithSamlIdp(
ProviderId: invalidProvider,
SpAcsUrl: spAcsUrl,
SamlResp: samlResp
)
XCTFail("Expected failure for invalid provider ID")
} catch {
let ns = error as NSError
if let code = AuthErrorCode(rawValue: ns.code) {
XCTAssert([.operationNotAllowed].contains(code),
"Unexpected code: \(code)")
} else {
XCTFail("Unexpected error: \(error)")
}
let desc = (ns.userInfo[NSLocalizedDescriptionKey] as? String ?? "").uppercased()
XCTAssert(
desc.contains("THE IDENTITY PROVIDER CONFIGURATION IS NOT FOUND."),
"Expected backend invalid provider message, got: \(desc)"
)
}
XCTAssertNil(Auth.auth().currentUser)
}

func testSignInWithSamlFailureInvalidResponse() async throws {
try? await deleteCurrentUserAsync()
let providerId = "saml.googleidp"
let spAcsUrl = "https://example.com/saml-acs"
let invalidSamlResp = "invalid%25"
do {
_ = try await Auth.auth().signInWithSamlIdp(
ProviderId: providerId,
SpAcsUrl: spAcsUrl,
SamlResp: invalidSamlResp
)
XCTFail("Expected failure for invalid SAMLResponse")
} catch {
let ns = error as NSError
if let code = AuthErrorCode(rawValue: ns.code) {
XCTAssert([.invalidCredential, .internalError].contains(code),
"Unexpected code: \(code)")
} else {
XCTFail("Unexpected error: \(error)")
}
let desc = (ns.userInfo[NSLocalizedDescriptionKey] as? String ?? "").uppercased()
XCTAssert(
desc.contains("UNABLE TO PARSE THE SAML TOKEN."),
"Expected backend invalid credential message, got: \(desc)"
)
}
XCTAssertNil(Auth.auth().currentUser)
}
}

#endif
Loading
Loading