-
Notifications
You must be signed in to change notification settings - Fork 11
/
Authgear.swift
573 lines (492 loc) · 19.4 KB
/
Authgear.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import AuthenticationServices
import Foundation
import SafariServices
public typealias AuthorizeCompletionHandler = (Result<AuthorizeResponse, Error>) -> Void
public typealias UserInfoCompletionHandler = (Result<UserInfo, Error>) -> Void
public typealias VoidCompletionHandler = (Result<Void, Error>) -> Void
struct AuthorizeOptions {
let redirectURI: String
let state: String?
let prompt: String?
let loginHint: String?
let uiLocales: [String]?
var urlScheme: String {
if let index = redirectURI.firstIndex(of: ":") {
return String(redirectURI[..<index])
}
return redirectURI
}
public init(
redirectURI: String,
state: String?,
prompt: String?,
loginHint: String?,
uiLocales: [String]?
) {
self.redirectURI = redirectURI
self.state = state
self.prompt = prompt
self.loginHint = loginHint
self.uiLocales = uiLocales
}
}
public struct UserInfo: Decodable {
enum CodingKeys: String, CodingKey {
case isAnonymous = "https://authgear.com/claims/user/is_anonymous"
case isVerified = "https://authgear.com/claims/user/is_verified"
case iss
case sub
}
let isAnonymous: Bool
let isVerified: Bool
let iss: String
let sub: String
}
public struct AuthorizeResponse {
public let userInfo: UserInfo
public let state: String?
}
public enum SessionState {
case loggedIn
case noSession
case unknown
}
public enum AuthgearPage: String {
case settings = "/settings"
case identity = "/settings/identities"
}
public protocol AuthgearDelegate: AnyObject {
func authgearRefreshTokenDidExpire(_ container: Authgear)
func authgearSessionStateDidChange(_ container: Authgear)
}
public class Authgear: NSObject {
let name: String
let apiClient: AuthAPIClient
let storage: ContainerStorage
let clientId: String
private let authenticationSessionProvider = AuthenticationSessionProvider()
private var authenticationSession: AuthenticationSession?
public private(set) var accessToken: String?
private var refreshToken: String?
private var expireAt: Date?
private let jwkStore = JWKStore()
private let workerQueue: DispatchQueue
public private(set) var sessionState: SessionState = .unknown
public weak var delegate: AuthgearDelegate?
public init(clientId: String, endpoint: String, name: String? = nil) {
self.clientId = clientId
self.name = name ?? "default"
apiClient = DefaultAuthAPIClient(endpoint: URL(string: endpoint)!)
storage = DefaultContainerStorage(storageDriver: KeychainStorageDriver())
workerQueue = DispatchQueue(label: "authgear:\(self.name)", qos: .utility)
}
public func configure(
skipRefreshAccessToken: Bool = false,
handler: VoidCompletionHandler? = nil
) {
workerQueue.async {
let refreshToken = Result { try self.storage.getRefreshToken(namespace: self.name) }
switch refreshToken {
case let .success(token):
if self.shouldRefreshAccessToken() && !skipRefreshAccessToken {
return self.refreshAccessToken(handler: handler)
}
DispatchQueue.main.async {
self.refreshToken = token
self.setSessionState(token == nil ? .noSession : .loggedIn)
handler?(.success(()))
}
case let .failure(error):
DispatchQueue.main.async {
handler?(.failure(error))
}
}
}
}
private func setSessionState(_ newState: SessionState) {
sessionState = newState
delegate?.authgearSessionStateDidChange(self)
}
private func authorizeEndpoint(_ options: AuthorizeOptions, verifier: CodeVerifier) throws -> URL {
let configuration = try apiClient.syncFetchOIDCConfiguration()
var queryItems = [URLQueryItem]()
queryItems.append(contentsOf: [
URLQueryItem(name: "response_type", value: "code"),
URLQueryItem(
name: "scope",
value: "openid offline_access https://authgear.com/scopes/full-access"
),
URLQueryItem(name: "code_challenge_method", value: "S256"),
URLQueryItem(name: "code_challenge", value: verifier.computeCodeChallenge())
])
queryItems.append(URLQueryItem(name: "client_id", value: clientId))
queryItems.append(URLQueryItem(name: "redirect_uri", value: options.redirectURI))
if let state = options.state {
queryItems.append(URLQueryItem(name: "state", value: state))
}
if let prompt = options.prompt {
queryItems.append(URLQueryItem(name: "prompt", value: prompt))
}
if let loginHint = options.loginHint {
queryItems.append(URLQueryItem(name: "login_hint", value: loginHint))
}
if let uiLocales = options.uiLocales {
queryItems.append(URLQueryItem(
name: "ui_locales",
value: uiLocales.joined(separator: " ")
))
}
var urlComponents = URLComponents(
url: configuration.authorizationEndpoint,
resolvingAgainstBaseURL: false
)!
urlComponents.queryItems = queryItems
return urlComponents.url!
}
private func authorize(
_ options: AuthorizeOptions,
handler: @escaping AuthorizeCompletionHandler
) {
let verifier = CodeVerifier()
let url = Result { try authorizeEndpoint(options, verifier: verifier) }
DispatchQueue.main.async {
switch url {
case let .success(url):
self.authenticationSession = self.authenticationSessionProvider.makeAuthenticationSession(
url: url,
callbackURLSchema: options.urlScheme,
completionHandler: { [weak self] result in
switch result {
case let .success(url):
self?.workerQueue.async {
self?.finishAuthorization(url: url, verifier: verifier, handler: handler)
}
case let .failure(error):
switch error {
case .canceledLogin:
return handler(.failure(AuthgearError.canceledLogin))
case let .sessionError(error):
return handler(.failure(AuthgearError.unexpectedError(error)))
}
}
}
)
self.authenticationSession?.start()
case let .failure(error):
handler(.failure(error))
}
}
}
private func finishAuthorization(
url: URL,
verifier: CodeVerifier,
handler: @escaping AuthorizeCompletionHandler
) {
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)!
let params = urlComponents.queryParams
let state = params["state"]
if let errorParams = params["error"] {
return handler(
.failure(AuthgearError.oauthError(
error: errorParams,
description: params["error_description"]
))
)
}
guard let code = params["code"] else {
return handler(
.failure(AuthgearError.oauthError(
error: "invalid_request",
description: "Missing parameter: code"
))
)
}
let redirectURI = { () -> String in
var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)!
urlComponents.fragment = nil
urlComponents.query = nil
return urlComponents.url!.absoluteString
}()
do {
let tokenResponse = try apiClient.syncRequestOIDCToken(
grantType: GrantType.authorizationCode,
clientId: clientId,
redirectURI: redirectURI,
code: code,
codeVerifier: verifier.value,
refreshToken: nil,
jwt: nil
)
let userInfo = try apiClient.syncRequestOIDCUserInfo(accessToken: tokenResponse.accessToken)
let result = persistSession(tokenResponse)
.map { AuthorizeResponse(userInfo: userInfo, state: state) }
return handler(result)
} catch {
return handler(.failure(error))
}
}
private func persistSession(_ tokenResponse: TokenResponse) -> Result<Void, Error> {
if let refreshToken = tokenResponse.refreshToken {
let result = Result { try self.storage.setRefreshToken(namespace: self.name, token: refreshToken) }
guard case .success = result else {
return result
}
}
DispatchQueue.main.async {
self.accessToken = tokenResponse.accessToken
self.refreshToken = tokenResponse.refreshToken
self.expireAt = Date(timeIntervalSinceNow: TimeInterval(tokenResponse.expiresIn))
self.setSessionState(.loggedIn)
}
return .success(())
}
private func cleanupSession(force: Bool) -> Result<Void, Error> {
if case let .failure(error) = Result(catching: { try storage.delRefreshToken(namespace: name) }) {
if !force {
return .failure(error)
}
}
if case let .failure(error) = Result(catching: { try storage.delAnonymousKeyId(namespace: name) }) {
if !force {
return .failure(error)
}
}
DispatchQueue.main.async {
self.accessToken = nil
self.refreshToken = nil
self.expireAt = nil
self.setSessionState(.noSession)
}
return .success(())
}
private func withMainQueueHandler<ResultType, ErrorType: Error>(
_ handler: @escaping (Result<ResultType, ErrorType>) -> Void
) -> ((Result<ResultType, ErrorType>) -> Void) {
return { result in
DispatchQueue.main.async {
handler(result)
}
}
}
public func authorize(
redirectURI: String,
state: String? = nil,
prompt: String? = "login",
loginHint: String? = nil,
uiLocales: [String]? = nil,
handler: @escaping AuthorizeCompletionHandler
) {
workerQueue.async {
self.authorize(
AuthorizeOptions(
redirectURI: redirectURI,
state: state,
prompt: prompt,
loginHint: loginHint,
uiLocales: uiLocales
),
handler: self.withMainQueueHandler(handler)
)
}
}
public func authenticateAnonymously(
handler: @escaping AuthorizeCompletionHandler
) {
let handler = withMainQueueHandler(handler)
workerQueue.async {
do {
let token = try self.apiClient.syncRequestOAuthChallenge(purpose: "anonymous_request").token
let keyId = try self.storage.getAnonymousKeyId(namespace: self.name) ?? UUID().uuidString
let tag = "com.authgear.keys.anonymous.\(keyId)"
let header: AnonymousJWTHeader
if let key = try self.jwkStore.loadKey(keyId: keyId, tag: tag) {
header = AnonymousJWTHeader(jwk: key, new: false)
} else {
let key = try self.jwkStore.generateKey(keyId: keyId, tag: tag)
header = AnonymousJWTHeader(jwk: key, new: true)
}
let payload = AnonymousJWYPayload(challenge: token, action: .auth)
let jwt = AnonymousJWT(header: header, payload: payload)
let privateKey = try self.jwkStore.loadPrivateKey(tag: tag)!
let signedJWT = try jwt.sign(with: JWTSigner(privateKey: privateKey))
let tokenResponse = try self.apiClient.syncRequestOIDCToken(
grantType: .anonymous,
clientId: self.clientId,
redirectURI: nil,
code: nil,
codeVerifier: nil,
refreshToken: nil,
jwt: signedJWT
)
let userInfo = try self.apiClient.syncRequestOIDCUserInfo(accessToken: tokenResponse.accessToken)
let result = self.persistSession(tokenResponse)
.flatMap { Result { try self.storage.setAnonymousKeyId(namespace: self.name, kid: keyId) } }
.map { AuthorizeResponse(userInfo: userInfo, state: nil) }
handler(result)
} catch {
handler(.failure(error))
}
}
}
public func promoteAnonymousUser(
redirectURI: String,
state: String? = nil,
uiLocales: [String]? = nil,
handler: @escaping AuthorizeCompletionHandler
) {
let handler = withMainQueueHandler(handler)
workerQueue.async {
do {
guard let keyId = try self.storage.getAnonymousKeyId(namespace: self.name) else {
return handler(.failure(AuthgearError.anonymousUserNotFound))
}
let tag = "com.authgear.keys.anonymous.\(keyId)"
let token = try self.apiClient.syncRequestOAuthChallenge(purpose: "anonymous_request").token
let header: AnonymousJWTHeader
if let key = try self.jwkStore.loadKey(keyId: keyId, tag: tag) {
header = AnonymousJWTHeader(jwk: key, new: false)
} else {
let key = try self.jwkStore.generateKey(keyId: keyId, tag: tag)
header = AnonymousJWTHeader(jwk: key, new: true)
}
let payload = AnonymousJWYPayload(challenge: token, action: .promote)
let jwt = AnonymousJWT(header: header, payload: payload)
let privateKey = try self.jwkStore.loadPrivateKey(tag: tag)!
let signedJWT = try jwt.sign(with: JWTSigner(privateKey: privateKey))
let loginHint = "https://authgear.com/login_hint?type=anonymous&jwt=\(signedJWT.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)"
self.authorize(
AuthorizeOptions(
redirectURI: redirectURI,
state: state,
prompt: "login",
loginHint: loginHint,
uiLocales: uiLocales
)
) { [weak self] result in
guard let this = self else { return }
switch result {
case let .success(response):
this.workerQueue.async {
let result = Result { try this.storage.delAnonymousKeyId(namespace: this.name) }
handler(result.map { response })
}
case let .failure(error):
handler(.failure(error))
}
}
} catch {
handler(.failure(error))
}
}
}
public func logout(
force: Bool = false,
redirectURI: String? = nil,
handler: @escaping (Result<Void, Error>) -> Void
) {
let handler = withMainQueueHandler(handler)
workerQueue.async {
do {
let token = try self.storage.getRefreshToken(
namespace: self.name
)
try self.apiClient.syncRequestOIDCRevocation(
refreshToken: token ?? ""
)
return handler(self.cleanupSession(force: force))
} catch {
if force {
return handler(self.cleanupSession(force: true))
}
return handler(.failure(error))
}
}
}
public func openUrl(
path: String,
handler: VoidCompletionHandler? = nil
) {
let handler = handler.map { h in withMainQueueHandler(h) }
let url = apiClient.endpoint.appendingPathComponent(path)
authenticationSession = authenticationSessionProvider.makeAuthenticationSession(
url: url,
callbackURLSchema: "",
completionHandler: { result in
switch result {
case .success:
handler?(.success(()))
case let .failure(error):
handler?(.failure(AuthgearError.unexpectedError(error)))
}
}
)
authenticationSession?.start()
}
public func open(page: AuthgearPage) {
openUrl(path: page.rawValue)
}
public func shouldRefreshAccessToken() -> Bool {
if refreshToken == nil {
return false
}
guard accessToken != nil,
let expireAt = self.expireAt,
expireAt.timeIntervalSinceNow.sign == .minus else {
return true
}
return false
}
public func refreshAccessToken(handler: VoidCompletionHandler? = nil) {
let handler = handler.map { h in withMainQueueHandler(h) }
workerQueue.async {
do {
guard let refreshToken = try self.storage.getRefreshToken(namespace: self.name) else {
handler?(self.cleanupSession(force: true))
return
}
let tokenResponse = try self.apiClient.syncRequestOIDCToken(
grantType: GrantType.refreshToken,
clientId: self.clientId,
redirectURI: nil,
code: nil,
codeVerifier: nil,
refreshToken: refreshToken,
jwt: nil
)
handler?(self.persistSession(tokenResponse))
} catch {
if let error = error as? AuthAPIClientError,
case let .oidcError(oidcError) = error,
oidcError.error == "invalid_grant" {
return DispatchQueue.main.async {
self.setSessionState(.noSession)
self.delegate?.authgearRefreshTokenDidExpire(self)
handler?(self.cleanupSession(force: true))
}
}
handler?(.failure(error))
}
}
}
public func fetchUserInfo(handler: @escaping UserInfoCompletionHandler) {
let handler = withMainQueueHandler(handler)
let fetchUserInfo = { (accessToken: String) in
self.workerQueue.async {
let result = Result { try self.apiClient.syncRequestOIDCUserInfo(accessToken: accessToken) }
handler(result)
}
}
if shouldRefreshAccessToken() {
refreshAccessToken { _ in
fetchUserInfo(self.accessToken ?? "")
}
} else {
fetchUserInfo(accessToken ?? "")
}
}
}
extension Authgear: AuthAPIClientDelegate {
func getAccessToken() -> String? {
accessToken
}
}