OAuthProvider.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import CommonCrypto
  15. import Foundation
  16. /// Utility class for constructing OAuth Sign In credentials.
  17. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  18. @objc(FIROAuthProvider) open class OAuthProvider: NSObject, FederatedAuthProvider {
  19. @objc public static let id = "OAuth"
  20. /// Array used to configure the OAuth scopes.
  21. @objc open var scopes: [String]?
  22. /// Dictionary used to configure the OAuth custom parameters.
  23. @objc open var customParameters: [String: String]?
  24. /// The provider ID indicating the specific OAuth provider this OAuthProvider instance represents.
  25. @objc public let providerID: String
  26. /// An instance of OAuthProvider corresponding to the given provider ID.
  27. /// - Parameters:
  28. /// - providerID: The provider ID of the IDP for which this auth provider instance will be
  29. /// configured.
  30. /// - Returns: An instance of OAuthProvider corresponding to the specified provider ID.
  31. @available(swift 1000.0) // Objective-C only API
  32. @objc(providerWithProviderID:) open class func provider(providerID: String) -> OAuthProvider {
  33. return OAuthProvider(providerID: providerID, auth: Auth.auth())
  34. }
  35. /// An instance of OAuthProvider corresponding to the given provider ID.
  36. /// - Parameters:
  37. /// - providerID: The provider ID of the IDP for which this auth provider instance will be
  38. /// configured.
  39. /// - Returns: An instance of OAuthProvider corresponding to the specified provider ID.
  40. public class func provider(providerID: AuthProviderID) -> OAuthProvider {
  41. return OAuthProvider(providerID: providerID.rawValue, auth: Auth.auth())
  42. }
  43. /// An instance of OAuthProvider corresponding to the given provider ID and auth instance.
  44. /// - Parameters:
  45. /// - providerID: The provider ID of the IDP for which this auth provider instance will be
  46. /// configured.
  47. /// - auth: The auth instance to be associated with the OAuthProvider instance.
  48. /// - Returns: An instance of OAuthProvider corresponding to the specified provider ID.
  49. @available(swift 1000.0) // Objective-C only API
  50. @objc(providerWithProviderID:auth:) open class func provider(providerID: String,
  51. auth: Auth) -> OAuthProvider {
  52. return OAuthProvider(providerID: providerID, auth: auth)
  53. }
  54. /// An instance of OAuthProvider corresponding to the given provider ID and auth instance.
  55. /// - Parameters:
  56. /// - providerID: The provider ID of the IDP for which this auth provider instance will be
  57. /// configured.
  58. /// - auth: The auth instance to be associated with the OAuthProvider instance.
  59. /// - Returns: An instance of OAuthProvider corresponding to the specified provider ID.
  60. public class func provider(providerID: AuthProviderID, auth: Auth) -> OAuthProvider {
  61. return OAuthProvider(providerID: providerID.rawValue, auth: auth)
  62. }
  63. /// Initializes an `OAuthProvider`.
  64. /// - Parameter providerID: The provider ID of the IDP for which this auth provider instance will
  65. /// be configured.
  66. /// - Parameter auth: The auth instance to be associated with the OAuthProvider instance.
  67. public init(providerID: String, auth: Auth = Auth.auth()) {
  68. if auth.requestConfiguration.emulatorHostAndPort == nil {
  69. if providerID == FacebookAuthProvider.id {
  70. fatalError("Sign in with Facebook is not supported via generic IDP; the Facebook TOS " +
  71. "dictate that you must use the Facebook iOS SDK for Facebook login.")
  72. }
  73. if providerID == AuthProviderID.apple.rawValue {
  74. fatalError("Sign in with Apple is not supported via generic IDP; You must use the Apple SDK" +
  75. " for Sign in with Apple.")
  76. }
  77. }
  78. self.auth = auth
  79. self.providerID = providerID
  80. scopes = [""]
  81. customParameters = [:]
  82. if let clientID = auth.app?.options.clientID {
  83. let reverseClientIDScheme = clientID.components(separatedBy: ".").reversed()
  84. .joined(separator: ".")
  85. if let urlTypes = auth.mainBundleUrlTypes,
  86. AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: reverseClientIDScheme,
  87. urlTypes: urlTypes) {
  88. callbackScheme = reverseClientIDScheme
  89. usingClientIDScheme = true
  90. return
  91. }
  92. }
  93. usingClientIDScheme = false
  94. if let appID = auth.app?.options.googleAppID {
  95. callbackScheme = "app-\(appID.replacingOccurrences(of: ":", with: "-"))"
  96. } else {
  97. fatalError("Missing googleAppID for constructing callbackScheme")
  98. }
  99. }
  100. /// Initializes an `OAuthProvider`.
  101. /// - Parameter providerID: The provider ID of the IDP for which this auth provider instance will
  102. /// be configured.
  103. /// - Parameter auth: The auth instance to be associated with the OAuthProvider instance.
  104. public convenience init(providerID: AuthProviderID, auth: Auth = Auth.auth()) {
  105. self.init(providerID: providerID.rawValue, auth: auth)
  106. }
  107. /// Creates an `AuthCredential` for the OAuth 2 provider identified by provider ID, ID
  108. /// token, and access token.
  109. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  110. /// - Parameter idToken: The IDToken associated with the Auth credential being created.
  111. /// - Parameter accessToken: The access token associated with the Auth credential be created, if
  112. /// available.
  113. /// - Returns: An AuthCredential for the specified provider ID, ID token and access token.
  114. @available(swift 1000.0) // Objective-C only API
  115. @objc(credentialWithProviderID:IDToken:accessToken:)
  116. public static func credential(withProviderID providerID: String,
  117. idToken: String,
  118. accessToken: String?) -> OAuthCredential {
  119. return OAuthCredential(withProviderID: providerID, idToken: idToken, accessToken: accessToken)
  120. }
  121. /// Creates an `AuthCredential` for the OAuth 2 provider identified by provider ID, ID
  122. /// token, and access token.
  123. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  124. /// - Parameter idToken: The IDToken associated with the Auth credential being created.
  125. /// - Parameter accessToken: The access token associated with the Auth credential be created, if
  126. /// available.
  127. /// - Returns: An AuthCredential for the specified provider ID, ID token and access token.
  128. public static func credential(providerID: AuthProviderID,
  129. idToken: String,
  130. accessToken: String? = nil) -> OAuthCredential {
  131. return OAuthCredential(
  132. withProviderID: providerID.rawValue,
  133. idToken: idToken,
  134. accessToken: accessToken
  135. )
  136. }
  137. /// Creates an `AuthCredential` for the OAuth 2 provider identified by provider ID, ID
  138. /// token, and access token.
  139. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  140. /// - Parameter accessToken: The access token associated with the Auth credential be created, if
  141. /// available.
  142. /// - Returns: An AuthCredential for the specified provider ID, ID token and access token.
  143. @available(swift 1000.0) // Objective-C only API
  144. @objc(credentialWithProviderID:accessToken:)
  145. public static func credential(withProviderID providerID: String,
  146. accessToken: String) -> OAuthCredential {
  147. return OAuthCredential(withProviderID: providerID, accessToken: accessToken)
  148. }
  149. /// Creates an `AuthCredential` for the OAuth 2 provider identified by provider ID using
  150. /// an ID token.
  151. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  152. /// - Parameter accessToken: The access token associated with the Auth credential be created
  153. /// - Returns: An AuthCredential.
  154. public static func credential(providerID: AuthProviderID,
  155. accessToken: String) -> OAuthCredential {
  156. return OAuthCredential(withProviderID: providerID.rawValue, accessToken: accessToken)
  157. }
  158. /// Creates an `AuthCredential` for that OAuth 2 provider identified by provider ID, ID
  159. /// token, raw nonce, and access token.
  160. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  161. /// - Parameter idToken: The IDToken associated with the Auth credential being created.
  162. /// - Parameter rawNonce: The raw nonce associated with the Auth credential being created.
  163. /// - Parameter accessToken: The access token associated with the Auth credential be created.
  164. /// - Returns: An AuthCredential for the specified provider ID, ID token and access token.
  165. @available(swift 1000.0) // Objective-C only API
  166. @objc(credentialWithProviderID:IDToken:rawNonce:accessToken:)
  167. public static func credential(withProviderID providerID: String, idToken: String,
  168. rawNonce: String,
  169. accessToken: String) -> OAuthCredential {
  170. return OAuthCredential(
  171. withProviderID: providerID,
  172. idToken: idToken,
  173. rawNonce: rawNonce,
  174. accessToken: accessToken
  175. )
  176. }
  177. /// Creates an `AuthCredential` for that OAuth 2 provider identified by providerID using
  178. /// an ID token and raw nonce.
  179. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  180. /// - Parameter idToken: The IDToken associated with the Auth credential being created.
  181. /// - Parameter rawNonce: The raw nonce associated with the Auth credential being created.
  182. /// - Returns: An AuthCredential.
  183. @available(swift 1000.0) // Objective-C only API
  184. @objc(credentialWithProviderID:IDToken:rawNonce:)
  185. public static func credential(withProviderID providerID: String, idToken: String,
  186. rawNonce: String) -> OAuthCredential {
  187. return OAuthCredential(withProviderID: providerID, idToken: idToken, rawNonce: rawNonce)
  188. }
  189. /// Creates an `AuthCredential` for that OAuth 2 provider identified by provider ID, ID
  190. /// token, raw nonce, and access token.
  191. /// - Parameter providerID: The provider ID associated with the Auth credential being created.
  192. /// - Parameter idToken: The IDToken associated with the Auth credential being created.
  193. /// - Parameter rawNonce: The raw nonce associated with the Auth credential being created.
  194. /// - Parameter accessToken: The access token associated with the Auth credential be created, if
  195. /// available.
  196. /// - Returns: An AuthCredential for the specified provider ID, ID token and access token.
  197. public static func credential(providerID: AuthProviderID, idToken: String,
  198. rawNonce: String,
  199. accessToken: String? = nil) -> OAuthCredential {
  200. return OAuthCredential(
  201. withProviderID: providerID.rawValue,
  202. idToken: idToken,
  203. rawNonce: rawNonce,
  204. accessToken: accessToken
  205. )
  206. }
  207. #if os(iOS)
  208. /// Used to obtain an auth credential via a mobile web flow.
  209. ///
  210. /// This method is available on iOS only.
  211. /// - Parameter uiDelegate: An optional UI delegate used to present the mobile web flow.
  212. /// - Parameter completion: Optionally; a block which is invoked asynchronously on the main
  213. /// thread when the mobile web flow is completed.
  214. open func getCredentialWith(_ uiDelegate: AuthUIDelegate?,
  215. completion: ((AuthCredential?, Error?) -> Void)? = nil) {
  216. guard let urlTypes = auth.mainBundleUrlTypes,
  217. AuthWebUtils.isCallbackSchemeRegistered(forCustomURLScheme: callbackScheme,
  218. urlTypes: urlTypes) else {
  219. fatalError(
  220. "Please register custom URL scheme \(callbackScheme) in the app's Info.plist file."
  221. )
  222. }
  223. kAuthGlobalWorkQueue.async { [weak self] in
  224. guard let self = self else { return }
  225. let eventID = AuthWebUtils.randomString(withLength: 10)
  226. let sessionID = AuthWebUtils.randomString(withLength: 10)
  227. let callbackOnMainThread: ((AuthCredential?, Error?) -> Void) = { credential, error in
  228. if let completion {
  229. DispatchQueue.main.async {
  230. completion(credential, error)
  231. }
  232. }
  233. }
  234. Task {
  235. do {
  236. guard let headfulLiteURL = try await self.getHeadfulLiteUrl(eventID: eventID,
  237. sessionID: sessionID) else {
  238. fatalError(
  239. "FirebaseAuth Internal Error: Both error and headfulLiteURL return are nil"
  240. )
  241. }
  242. let callbackMatcher: (URL?) -> Bool = { callbackURL in
  243. AuthWebUtils.isExpectedCallbackURL(callbackURL,
  244. eventID: eventID,
  245. authType: "signInWithRedirect",
  246. callbackScheme: self.callbackScheme)
  247. }
  248. self.auth.authURLPresenter.present(headfulLiteURL,
  249. uiDelegate: uiDelegate,
  250. callbackMatcher: callbackMatcher) { callbackURL, error in
  251. if let error {
  252. callbackOnMainThread(nil, error)
  253. return
  254. }
  255. guard let callbackURL else {
  256. fatalError("FirebaseAuth Internal Error: Both error and callbackURL return are nil")
  257. }
  258. let (oAuthResponseURLString, error) = self.oAuthResponseForURL(url: callbackURL)
  259. if let error {
  260. callbackOnMainThread(nil, error)
  261. return
  262. }
  263. guard let oAuthResponseURLString else {
  264. fatalError(
  265. "FirebaseAuth Internal Error: Both error and oAuthResponseURLString return are nil"
  266. )
  267. }
  268. let credential = OAuthCredential(withProviderID: self.providerID,
  269. sessionID: sessionID,
  270. OAuthResponseURLString: oAuthResponseURLString)
  271. callbackOnMainThread(credential, nil)
  272. }
  273. } catch {
  274. callbackOnMainThread(nil, error)
  275. }
  276. }
  277. }
  278. }
  279. /// Used to obtain an auth credential via a mobile web flow.
  280. /// This method is available on iOS only.
  281. /// - Parameter uiDelegate: An optional UI delegate used to present the mobile web flow.
  282. /// - Parameter completionHandler: Optionally; a block which is invoked
  283. /// asynchronously on the main thread when the mobile web flow is
  284. /// completed.
  285. @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
  286. @objc(getCredentialWithUIDelegate:completion:)
  287. @MainActor
  288. open func credential(with uiDelegate: AuthUIDelegate?) async throws -> AuthCredential {
  289. return try await withCheckedThrowingContinuation { continuation in
  290. getCredentialWith(uiDelegate) { credential, error in
  291. if let credential = credential {
  292. continuation.resume(returning: credential)
  293. } else {
  294. continuation.resume(throwing: error!) // TODO: Change to ?? and generate unknown error
  295. }
  296. }
  297. }
  298. }
  299. #endif
  300. /// Creates an `AuthCredential` for the Sign in with Apple OAuth 2 provider identified by ID
  301. /// token, raw nonce, and full name.This method is specific to the Sign in with Apple OAuth 2
  302. /// provider as this provider requires the full name to be passed explicitly.
  303. /// - Parameter idToken: The IDToken associated with the Sign in with Apple Auth credential being
  304. /// created.
  305. /// - Parameter rawNonce: The raw nonce associated with the Sign in with Apple Auth credential
  306. /// being created.
  307. /// - Parameter fullName: The full name associated with the Sign in with Apple Auth credential
  308. /// being created.
  309. /// - Returns: An AuthCredential.
  310. @objc(appleCredentialWithIDToken:rawNonce:fullName:)
  311. public static func appleCredential(withIDToken idToken: String,
  312. rawNonce: String?,
  313. fullName: PersonNameComponents?) -> OAuthCredential {
  314. return OAuthCredential(withProviderID: AuthProviderID.apple.rawValue,
  315. idToken: idToken,
  316. rawNonce: rawNonce,
  317. fullName: fullName)
  318. }
  319. // MARK: - Private Methods
  320. /// Parses the redirected URL and returns a string representation of the OAuth response URL.
  321. /// - Parameter url: The url to be parsed for an OAuth response URL.
  322. /// - Returns: The OAuth response if successful.
  323. private func oAuthResponseForURL(url: URL) -> (String?, Error?) {
  324. var urlQueryItems = AuthWebUtils.dictionary(withHttpArgumentsString: url.query)
  325. if let item = urlQueryItems["deep_link_id"],
  326. let deepLinkURL = URL(string: item) {
  327. urlQueryItems = AuthWebUtils.dictionary(withHttpArgumentsString: deepLinkURL.query)
  328. if let queryItemLink = urlQueryItems["link"] {
  329. return (queryItemLink, nil)
  330. }
  331. }
  332. if let errorData = urlQueryItems["firebaseError"]?.data(using: .utf8) {
  333. do {
  334. let error = try JSONSerialization.jsonObject(with: errorData) as? [String: Any]
  335. let code = (error?["code"] as? String) ?? "missing code"
  336. let message = (error?["message"] as? String) ?? "missing message"
  337. return (nil, AuthErrorUtils.urlResponseError(code: code, message: message))
  338. } catch {
  339. return (nil, AuthErrorUtils.JSONSerializationError(underlyingError: error))
  340. }
  341. }
  342. return (nil, AuthErrorUtils.webSignInUserInteractionFailure(
  343. reason: "SignIn failed with unparseable firebaseError"
  344. ))
  345. }
  346. /// Constructs a URL used for opening a headful-lite flow using a given event
  347. /// ID and session ID.
  348. /// - Parameter eventID: The event ID used for this purpose.
  349. /// - Parameter sessionID: The session ID used when completing the headful lite flow.
  350. /// - Returns: A url.
  351. private func getHeadfulLiteUrl(eventID: String,
  352. sessionID: String) async throws -> URL? {
  353. let authDomain = try await AuthWebUtils
  354. .fetchAuthDomain(withRequestConfiguration: auth.requestConfiguration, backend: auth.backend)
  355. let bundleID = Bundle.main.bundleIdentifier
  356. let clientID = auth.app?.options.clientID
  357. let appID = auth.app?.options.googleAppID
  358. let apiKey = auth.requestConfiguration.apiKey
  359. let tenantID = auth.tenantID
  360. let appCheck = auth.requestConfiguration.appCheck
  361. // TODO: Should we fail if these strings are empty? Only ibi was explicit in ObjC.
  362. var urlArguments = ["apiKey": apiKey,
  363. "authType": "signInWithRedirect",
  364. "ibi": bundleID ?? "",
  365. "sessionId": hash(forString: sessionID),
  366. "v": AuthBackend.authUserAgent(),
  367. "eventId": eventID,
  368. "providerId": providerID]
  369. if usingClientIDScheme {
  370. urlArguments["clientId"] = clientID
  371. } else {
  372. urlArguments["appId"] = appID
  373. }
  374. if let tenantID {
  375. urlArguments["tid"] = tenantID
  376. }
  377. if let scopes, scopes.count > 0 {
  378. urlArguments["scopes"] = scopes.joined(separator: ",")
  379. }
  380. if let customParameters, customParameters.count > 0 {
  381. do {
  382. let customParametersJSONData = try JSONSerialization
  383. .data(withJSONObject: customParameters)
  384. let rawJson = String(decoding: customParametersJSONData, as: UTF8.self)
  385. urlArguments["customParameters"] = rawJson
  386. } catch {
  387. throw AuthErrorUtils.JSONSerializationError(underlyingError: error)
  388. }
  389. }
  390. if let languageCode = auth.requestConfiguration.languageCode {
  391. urlArguments["hl"] = languageCode
  392. }
  393. let argumentsString = httpArgumentsString(forArgsDictionary: urlArguments)
  394. var urlString: String
  395. if (auth.requestConfiguration.emulatorHostAndPort) != nil {
  396. urlString = "http://\(authDomain)/emulator/auth/handler?\(argumentsString)"
  397. } else {
  398. urlString = "https://\(authDomain)/__/auth/handler?\(argumentsString)"
  399. }
  400. guard let percentEncoded = urlString.addingPercentEncoding(
  401. withAllowedCharacters: CharacterSet.urlFragmentAllowed
  402. ) else {
  403. fatalError("Internal Auth Error: failed to percent encode a string")
  404. }
  405. var components = URLComponents(string: percentEncoded)
  406. if let appCheck {
  407. let tokenResult = await appCheck.getToken(forcingRefresh: false)
  408. if let error = tokenResult.error {
  409. AuthLog.logWarning(code: "I-AUT000018",
  410. message: "Error getting App Check token; using placeholder " +
  411. "token instead. Error: \(error)")
  412. }
  413. let appCheckTokenFragment = "fac=\(tokenResult.token)"
  414. components?.fragment = appCheckTokenFragment
  415. }
  416. return components?.url
  417. }
  418. /// Returns the SHA256 hash representation of a given string object.
  419. /// - Parameter string: The string for which a SHA256 hash is desired.
  420. /// - Returns: An hexadecimal string representation of the SHA256 hash.
  421. private func hash(forString string: String) -> String {
  422. guard let sessionIdData = string.data(using: .utf8) as? NSData else {
  423. fatalError("FirebaseAuth Internal error: Failed to create hash for sessionID")
  424. }
  425. let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
  426. var hash = [UInt8](repeating: 0, count: digestLength)
  427. CC_SHA256(sessionIdData.bytes, UInt32(sessionIdData.length), &hash)
  428. let dataHash = NSData(bytes: hash, length: digestLength)
  429. var bytes = [UInt8](repeating: 0, count: digestLength)
  430. dataHash.getBytes(&bytes, length: digestLength)
  431. var hexString = ""
  432. for byte in bytes {
  433. hexString += String(format: "%02x", UInt8(byte))
  434. }
  435. return hexString
  436. }
  437. private func httpArgumentsString(forArgsDictionary argsDictionary: [String: String]) -> String {
  438. var argsString: [String] = []
  439. for (key, value) in argsDictionary {
  440. let keyString = AuthWebUtils.string(byUnescapingFromURLArgument: key)
  441. let valueString = AuthWebUtils.string(byUnescapingFromURLArgument: value.description)
  442. argsString.append("\(keyString)=\(valueString)")
  443. }
  444. return argsString.joined(separator: "&")
  445. }
  446. private let auth: Auth
  447. private let callbackScheme: String
  448. private let usingClientIDScheme: Bool
  449. }