Skip to content

Commit e247b0a

Browse files
author
Nelson Cardaci
committed
adds JWT parser
1 parent cf94599 commit e247b0a

File tree

2 files changed

+58
-15
lines changed

2 files changed

+58
-15
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//
2+
// File.swift
3+
//
4+
//
5+
// Created by Nelson Cardaci on 12/09/2019.
6+
//
7+
8+
import Foundation
9+
struct JWT {
10+
func decode<T: Codable>(jwtToken jwt: String) -> T? {
11+
12+
func base64UrlDecode(_ value: String) -> Data? {
13+
var base64 = value
14+
.replacingOccurrences(of: "-", with: "+")
15+
.replacingOccurrences(of: "_", with: "/")
16+
17+
let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8))
18+
let requiredLength = 4 * ceil(length / 4.0)
19+
let paddingLength = requiredLength - length
20+
if paddingLength > 0 {
21+
let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0)
22+
base64 = base64 + padding
23+
}
24+
return Data(base64Encoded: base64, options: .ignoreUnknownCharacters)
25+
}
26+
27+
func decodeJWTPart(_ value: String) -> T? {
28+
guard let data = base64UrlDecode(value) else {
29+
return nil
30+
}
31+
do {
32+
return try JSONDecoder().decode(T.self, from: data)
33+
} catch {
34+
print("Error while decoding json:\(error.localizedDescription )")
35+
return nil
36+
}
37+
38+
}
39+
40+
let segments = jwt.components(separatedBy: ".")
41+
return decodeJWTPart(segments[1])
42+
}
43+
}
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
//import XCTest
2-
//@testable import Marvin
3-
//
4-
//final class MarvinTests: XCTestCase {
5-
// func testExample() {
6-
// // This is an example of a functional test case.
7-
// // Use XCTAssert and related functions to verify your tests produce the correct
8-
// // results.
9-
// XCTAssertEqual(Marvin().text, "Hello, World!")
10-
// }
11-
//
12-
// static var allTests = [
13-
// ("testExample", testExample),
14-
// ]
15-
//}
1+
import XCTest
2+
@testable import Marvin
3+
4+
final class MarvinTests: XCTestCase {
5+
func testExample() {
6+
// This is an example of a functional test case.
7+
// Use XCTAssert and related functions to verify your tests produce the correct
8+
// results.
9+
XCTAssertEqual(Marvin, "Hello, World!")
10+
}
11+
12+
static var allTests = [
13+
("testExample", testExample),
14+
]
15+
}

0 commit comments

Comments
 (0)