diff --git a/Sources/mpc-core-kit-swift/Helper.swift b/Sources/mpc-core-kit-swift/Helper.swift index 2eb5ff4..8097b79 100644 --- a/Sources/mpc-core-kit-swift/Helper.swift +++ b/Sources/mpc-core-kit-swift/Helper.swift @@ -11,7 +11,6 @@ import tkey import BigInt import curveSecp256k1 import FetchNodeDetails - import SingleFactorAuth @@ -79,3 +78,32 @@ public extension Web3AuthNetwork { return convertWeb3AuthNetworkToTorusNetWork(network: self) } } + +public func parseToken(jwtToken jwt: String) -> [String: Any] { + let segments = jwt.components(separatedBy: ".") + return decodeJWTPart(segments[1]) ?? [:] +} + +func base64UrlDecode(_ value: String) -> Data? { + var base64 = value + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + + let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8)) + let requiredLength = 4 * ceil(length / 4.0) + let paddingLength = requiredLength - length + if paddingLength > 0 { + let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0) + base64 = base64 + padding + } + return Data(base64Encoded: base64, options: .ignoreUnknownCharacters) +} + +func decodeJWTPart(_ value: String) -> [String: Any]? { + guard let bodyData = base64UrlDecode(value), + let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), let payload = json as? [String: Any] else { + return nil + } + + return payload +} diff --git a/Tests/mpc-kit-swiftTests/mpc_kit_swiftTests.swift b/Tests/mpc-kit-swiftTests/mpc_kit_swiftTests.swift index aa8a301..de9b7af 100644 --- a/Tests/mpc-kit-swiftTests/mpc_kit_swiftTests.swift +++ b/Tests/mpc-kit-swiftTests/mpc_kit_swiftTests.swift @@ -3,6 +3,7 @@ import XCTest import JWTKit import curveSecp256k1 import SingleFactorAuth +import Foundation // JWT payload structure. struct TestPayload: JWTPayload, Equatable { @@ -83,6 +84,7 @@ func mockLogin2 (email:String) throws -> String { let payload = TestPayload(subject: SubjectClaim(stringLiteral: subject), expiration: ExpirationClaim(value: modifiedDate), audience: "torus-key-test", isAdmin: false, emailVerified: true, issuer: "torus-key-test", iat: IssuedAtClaim(value: Date()), email: email) let jwt = try signers.sign(payload) + return jwt } catch { throw error @@ -187,4 +189,18 @@ final class mpc_kit_swiftTests: XCTestCase { let hash2 = try Data(hex: "010203040506").sha3(varient: Variants.KECCAK256) let signatures2 = try await coreKitInstance2.tssSign(message: hash2) } + + func testparseToken() async throws { + let email = "testiosEmail004" + let data = try mockLogin2(email: email) + let token = data + let parsedToken = parseToken(jwtToken: token); + print("Parsed Token: \(parsedToken)"); + if let parsedEmail = parsedToken["email"] as? String { + XCTAssertEqual(parsedEmail, email); + print(parsedEmail); + } else { + XCTFail("Verifier ID not matching.") + } + } }