AuthTokenResult.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 Foundation
  15. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  16. extension AuthTokenResult: NSSecureCoding {}
  17. /// A data class containing the ID token JWT string and other properties associated with the
  18. /// token including the decoded payload claims.
  19. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  20. @objc(FIRAuthTokenResult) open class AuthTokenResult: NSObject {
  21. /// Stores the JWT string of the ID token.
  22. @objc open var token: String
  23. /// Stores the ID token's expiration date.
  24. @objc open var expirationDate: Date
  25. /// Stores the ID token's authentication date.
  26. ///
  27. /// This is the date the user was signed in and NOT the date the token was refreshed.
  28. @objc open var authDate: Date
  29. /// Stores the date that the ID token was issued.
  30. ///
  31. /// This is the date last refreshed and NOT the last authentication date.
  32. @objc open var issuedAtDate: Date
  33. /// Stores sign-in provider through which the token was obtained.
  34. @objc open var signInProvider: String
  35. /// Stores sign-in second factor through which the token was obtained.
  36. @objc open var signInSecondFactor: String
  37. /// Stores the entire payload of claims found on the ID token.
  38. ///
  39. /// This includes the standard
  40. /// reserved claims as well as custom claims set by the developer via the Admin SDK.
  41. @objc open var claims: [String: Any]
  42. private class func getTokenPayloadData(_ token: String) throws -> Data {
  43. let tokenStringArray = token.components(separatedBy: ".")
  44. // The JWT should have three parts, though we only use the second in this method.
  45. if tokenStringArray.count != 3 {
  46. throw AuthErrorUtils.malformedJWTError(token: token, underlyingError: nil)
  47. }
  48. /// The token payload is always the second index of the array.
  49. let IDToken = tokenStringArray[1]
  50. /// Convert the base64URL encoded string to a base64 encoded string.
  51. /// * Replace "_" with "/"
  52. /// * Replace "-" with "+"
  53. var tokenPayload = IDToken.replacingOccurrences(of: "_", with: "/")
  54. .replacingOccurrences(of: "-", with: "+")
  55. // Pad the token payload with "=" signs if the payload's length is not a multiple of 4.
  56. if tokenPayload.count % 4 != 0 {
  57. let length = tokenPayload.count + (4 - tokenPayload.count % 4)
  58. tokenPayload = tokenPayload.padding(toLength: length, withPad: "=", startingAt: 0)
  59. }
  60. guard let data = Data(base64Encoded: tokenPayload, options: [.ignoreUnknownCharacters]) else {
  61. throw AuthErrorUtils.malformedJWTError(token: token, underlyingError: nil)
  62. }
  63. return data
  64. }
  65. private class func getTokenPayloadDictionary(_ token: String,
  66. _ payloadData: Data) throws -> [String: Any] {
  67. do {
  68. if let dictionary = try JSONSerialization.jsonObject(
  69. with: payloadData,
  70. options: [.mutableContainers, .allowFragments]
  71. ) as? [String: Any] {
  72. return dictionary
  73. } else {
  74. return [:]
  75. }
  76. } catch {
  77. throw AuthErrorUtils.malformedJWTError(token: token, underlyingError: error)
  78. }
  79. }
  80. private class func getJWT(_ token: String, _ payloadData: Data) throws -> JWT {
  81. // These are dates since 00:00:00 January 1 1970, as described by the Terminology section in
  82. // the JWT spec. https://tools.ietf.org/html/rfc7519
  83. let decoder = JSONDecoder()
  84. decoder.dateDecodingStrategy = .secondsSince1970
  85. decoder.keyDecodingStrategy = .convertFromSnakeCase
  86. guard let jwt = try? decoder.decode(JWT.self, from: payloadData) else {
  87. throw AuthErrorUtils.malformedJWTError(token: token, underlyingError: nil)
  88. }
  89. return jwt
  90. }
  91. /// Parse a token string to a structured token.
  92. /// - Parameter token: The token string to parse.
  93. /// - Returns: A structured token result.
  94. class func tokenResult(token: String) throws -> AuthTokenResult {
  95. let payloadData = try getTokenPayloadData(token)
  96. let claims = try getTokenPayloadDictionary(token, payloadData)
  97. let jwt = try getJWT(token, payloadData)
  98. return AuthTokenResult(token: token, jwt: jwt, claims: claims)
  99. }
  100. private init(token: String, jwt: JWT, claims: [String: Any]) {
  101. self.token = token
  102. expirationDate = jwt.exp
  103. authDate = jwt.authTime
  104. issuedAtDate = jwt.iat
  105. signInProvider = jwt.firebase.signInProvider
  106. signInSecondFactor = jwt.firebase.signInSecondFactor ?? ""
  107. self.claims = claims
  108. }
  109. // MARK: Secure Coding
  110. private static let kTokenKey = "token"
  111. public static let supportsSecureCoding = true
  112. public func encode(with coder: NSCoder) {
  113. coder.encode(token, forKey: AuthTokenResult.kTokenKey)
  114. }
  115. public required convenience init?(coder: NSCoder) {
  116. guard let token = coder.decodeObject(
  117. of: [NSString.self],
  118. forKey: AuthTokenResult.kTokenKey
  119. ) as? String else {
  120. return nil
  121. }
  122. guard let payloadData = try? AuthTokenResult.getTokenPayloadData(token),
  123. let claims = try? AuthTokenResult.getTokenPayloadDictionary(token, payloadData),
  124. let jwt = try? AuthTokenResult.getJWT(token, payloadData) else {
  125. return nil
  126. }
  127. self.init(token: token, jwt: jwt, claims: claims)
  128. }
  129. }
  130. private struct JWT: Decodable {
  131. struct FirebasePayload: Decodable {
  132. let signInProvider: String
  133. let signInSecondFactor: String?
  134. }
  135. let exp: Date
  136. let authTime: Date
  137. let iat: Date
  138. let firebase: FirebasePayload
  139. }