OAuthProvider.swift 19 KB

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