-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthenticatorImpl.swift
529 lines (425 loc) · 18 KB
/
AuthenticatorImpl.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
// swiftlint:disable file_length
import AppAuth
/*
* The class for handling OAuth operations
*/
// swiftlint:disable type_body_length
class AuthenticatorImpl: Authenticator {
private let configuration: OAuthConfiguration
private var metadata: OIDServiceConfiguration?
private var currentOAuthSession: OIDExternalUserAgentSession?
private var tokenStorage: TokenStorage
private var loginResponseHandler: LoginResponseHandler
private var logoutResponseHandler: LogoutResponseHandler
private let concurrencyHandler: ConcurrentActionHandler
/*
* Initialise from input
*/
init (configuration: OAuthConfiguration) {
self.configuration = configuration
self.tokenStorage = TokenStorage()
self.loginResponseHandler = LoginResponseHandler()
self.logoutResponseHandler = LogoutResponseHandler()
self.concurrencyHandler = ConcurrentActionHandler()
}
/*
* One time initialization on application startup
*/
func initialize() async throws {
// Load OpenID Connect metadata
try await getMetadata()
// Load tokens from storage
self.tokenStorage.loadTokens()
}
/*
* Download OpenID Connect metadata and return it to the caller
*/
private func getMetadata() async throws {
// Do nothing if already loaded
if self.metadata != nil {
return
}
// Get the metadata endpoint as a URL object
guard let issuerUrl = URL(string: self.configuration.authority) else {
let message = "Unable to create URL from \(self.configuration.authority)"
throw ErrorFactory.fromMessage(message: message)
}
// Try to download metadata
return try await withCheckedThrowingContinuation { continuation in
OIDAuthorizationService.discoverConfiguration(forIssuer: issuerUrl) { metadata, error in
if error != nil {
// Report errors
continuation.resume(throwing: ErrorFactory.fromMetadataLookupError(error: error!))
} else {
// Indicate success
self.metadata = metadata
continuation.resume()
}
}
}
}
/*
* Try to get an access token, which most commonly involves returning the current one
*/
func getAccessToken() -> String? {
return self.tokenStorage.getTokens()?.accessToken
}
/*
* Try to refresh an access token
*/
func synchronizedRefreshAccessToken() async throws -> String {
let refreshToken = self.tokenStorage.getTokens()?.refreshToken
// Execute the refresh token grant message and manage concurrency
if refreshToken != nil {
try await self.concurrencyHandler.execute(action: self.performRefreshTokenGrant)
}
// Reload and see if we now have a new access token
let accessToken = self.tokenStorage.getTokens()?.accessToken
if accessToken != nil {
// Return the new access token if the refresh succeeded
return accessToken!
} else {
// Otherwise indicate a login is required
throw ErrorFactory.fromLoginRequired()
}
}
/*
* Return the logged in status
*/
func isLoggedIn() -> Bool {
return self.tokenStorage.getTokens() != nil
}
/*
* The OAuth entry point for login processing runs on the UI thread
*/
func startLoginRedirect(viewController: UIViewController) throws {
do {
// Get the redirect address into a URL object
let redirectUri = self.getLoginRedirectUri()
guard let loginRedirectUri = URL(string: redirectUri) else {
let message = "Error creating URL for : \(redirectUri)"
throw ErrorFactory.fromMessage(message: message)
}
// Set additional parameters such as acr_values if applicable
let additionalParameters = [String: String]()
// Build the authorization request
let scopesArray = self.configuration.scope.components(separatedBy: " ")
let request = OIDAuthorizationRequest(
configuration: self.metadata!,
clientId: self.configuration.clientId,
clientSecret: nil,
scopes: scopesArray,
redirectURL: loginRedirectUri,
responseType: OIDResponseTypeCode,
additionalParameters: additionalParameters)
// Do the redirect
self.currentOAuthSession = OIDAuthorizationService.present(
request,
presenting: viewController,
callback: self.loginResponseHandler.callback)
} catch {
// Handle errors
self.currentOAuthSession = nil
throw ErrorFactory.fromLoginRequestError(error: error)
}
}
/*
* Complete login processing on a background thread
*/
func handleLoginResponse() async throws -> OIDAuthorizationResponse {
do {
return try await self.loginResponseHandler.waitForCallback()
} catch {
self.currentOAuthSession = nil
if self.isCancelledError(error: error) {
throw ErrorFactory.fromRedirectCancelled()
}
throw ErrorFactory.fromLoginResponseError(error: error)
}
}
/*
* The authorization code grant runs on a background thread
*/
func finishLogin(authResponse: OIDAuthorizationResponse) async throws {
self.currentOAuthSession = nil
let request = authResponse.tokenExchangeRequest()
return try await withCheckedThrowingContinuation { continuation in
// Make the authorization code grant request
OIDAuthorizationService.perform(
request!,
originalAuthorizationResponse: authResponse) { tokenResponse, error in
if error != nil {
// Throw errors
let uiError = ErrorFactory.fromTokenError(
error: error!,
errorCode: ErrorCodes.authorizationCodeGrantFailed)
continuation.resume(throwing: uiError)
}
// Save the tokens to storage
self.saveTokens(tokenResponse: tokenResponse!)
continuation.resume()
}
}
}
/*
* The OAuth entry point for logout processing
*/
func startLogoutRedirect(viewController: UIViewController) throws {
// Do nothing if already logged out
let tokenData = self.tokenStorage.getTokens()
if tokenData == nil || tokenData!.idToken == nil {
return
}
do {
// Clear tokens
let idToken = tokenData!.idToken!
self.clearLoginState()
// Get the post logout address as a URL object
let postLogoutUrl = self.getPostLogoutRedirectUri()
guard let postLogoutRedirectUri = URL(string: postLogoutUrl) else {
let message = "Error creating URL for : \(postLogoutUrl)"
throw ErrorFactory.fromMessage(message: message)
}
// Create an object to manage provider differences
let logoutManager = self.createLogoutManager()
// If required, create an updated metadata object with an end session endpoint
let metadataWithEndSessionEndpoint = try logoutManager.updateMetadata(
metadata: self.metadata!)
// Build the end session request
let request = logoutManager.createEndSessionRequest(
metadata: metadataWithEndSessionEndpoint,
idToken: idToken,
postLogoutRedirectUri: postLogoutRedirectUri)
// Do the logout redirect
let agent = OIDExternalUserAgentIOS(presenting: viewController)
self.currentOAuthSession = OIDAuthorizationService.present(
request,
externalUserAgent: agent!,
callback: self.logoutResponseHandler.callback)
} catch {
// Handle errors
self.currentOAuthSession = nil
throw ErrorFactory.fromLogoutRequestError(error: error)
}
}
/*
* Process the logout response and free resources
*/
func handleLogoutResponse() async throws -> OIDEndSessionResponse? {
do {
return try await self.logoutResponseHandler.waitForCallback()
} catch {
self.currentOAuthSession = nil
// If the user cancels the logout we throw a special error
if self.isCancelledError(error: error) {
throw ErrorFactory.fromRedirectCancelled()
}
// Treat logout state mismatch errors as benign
if self.isLogoutStateMismatchError(error: error) {
return nil
}
throw ErrorFactory.fromLogoutRequestError(error: error)
}
}
/*
* Return true if the URL matches an OAuth response reactivation URL from the interstitial page
*/
func isOAuthResponse(responseUrl: URL) -> Bool {
return
responseUrl.absoluteString.lowercased().starts(with: self.getLoginReactivateUri().lowercased()) ||
responseUrl.absoluteString.lowercased().starts(with: self.getPostLogoutReactivateUri().lowercased())
}
/*
* Resume a login or logout operation
* We need to work around this AppAuth iOS issue: https://github.com/openid/AppAuth-iOS/issues/356
* To do so we must resume on the original redirect URI so some string replacement is needed
*/
func resumeOperation(responseUrl: URL) {
if self.currentOAuthSession != nil {
var resumeUrl: String?
let queryString = responseUrl.query ?? ""
// If we are invoked on the login activation URL then resume on the login redirect URI
let loginActivationUri = self.getLoginReactivateUri().lowercased()
let loginRedirectUri = self.getLoginRedirectUri().lowercased()
if responseUrl.absoluteString.lowercased().starts(with: loginActivationUri) {
resumeUrl = "\(loginRedirectUri)?\(queryString)"
}
// If we are invoked on the logout activation URL then resume on the logout redirect URI
let logoutActivationUri = self.getPostLogoutReactivateUri().lowercased()
let logoutRedirectUri = self.getPostLogoutRedirectUri().lowercased()
if responseUrl.absoluteString.lowercased().starts(with: logoutActivationUri) {
resumeUrl = "\(logoutRedirectUri)?\(queryString)"
}
// Resume OAuth processing with the URL
if resumeUrl != nil {
self.currentOAuthSession!.resumeExternalUserAgentFlow(
with: URL(string: resumeUrl!)!)
}
}
}
/*
* Allow the login state to be cleared when required
*/
func clearLoginState() {
self.tokenStorage.removeTokens()
}
/*
* A hacky method for testing, to update token storage to make the access token act like it is expired
*/
func expireAccessToken() {
self.tokenStorage.expireAccessToken()
}
/*
* A hacky method for testing, to update token storage to make the refresh token act like it is expired
*/
func expireRefreshToken() {
self.tokenStorage.expireRefreshToken()
}
/*
* A synchronised method to do the work of the refresh token grant
*/
private func performRefreshTokenGrant() async throws {
let tokenData = self.tokenStorage.getTokens()
// Create the refresh token grant request
let request = OIDTokenRequest(
configuration: self.metadata!,
grantType: OIDGrantTypeRefreshToken,
authorizationCode: nil,
redirectURL: nil,
clientID: self.configuration.clientId,
clientSecret: nil,
scope: nil,
refreshToken: tokenData!.refreshToken!,
codeVerifier: nil,
additionalParameters: nil)
return try await withCheckedThrowingContinuation { continuation in
OIDAuthorizationService.perform(request) { tokenResponse, error in
// Handle errors
if error != nil {
if self.matchesAppAuthError(
error: error!,
domain: OIDOAuthTokenErrorDomain,
code: OIDErrorCodeOAuth.invalidGrant.rawValue) {
// If we get an invalid_grant error it means the refresh token has expired
// In this case clear tokens and return, which will trigger a login redirect
self.clearLoginState()
continuation.resume()
return
}
// Handle other errors
let uiError = ErrorFactory.fromTokenError(
error: error!,
errorCode: ErrorCodes.refreshTokenGrantFailed)
continuation.resume(throwing: uiError)
return
}
// Make a sanity check to ensure we have tokens
if tokenResponse == nil || tokenResponse!.accessToken == nil {
let message = "No tokens were received in the Refresh Token Grant message"
continuation.resume(throwing: ErrorFactory.fromMessage(message: message))
return
}
// Save received tokens and return success
self.saveTokens(tokenResponse: tokenResponse!)
continuation.resume()
}
}
}
/*
* Save tokens from an authoprization code grant or refresh token grant response
*/
private func saveTokens(tokenResponse: OIDTokenResponse) {
// Create token data from the response
let newTokenData = TokenData()
newTokenData.accessToken = tokenResponse.accessToken!
if tokenResponse.refreshToken != nil {
newTokenData.refreshToken = tokenResponse.refreshToken!
}
if tokenResponse.idToken != nil {
newTokenData.idToken = tokenResponse.idToken!
}
// Handle missing tokens in the token response
let oldTokenData = self.tokenStorage.getTokens()
if oldTokenData != nil {
// Maintain the existing refresh token unless we received a new 'rolling' refresh token
if newTokenData.refreshToken == nil {
newTokenData.refreshToken = oldTokenData!.refreshToken
}
// Maintain the existing id token if required, which may be needed for logout
if newTokenData.idToken == nil {
newTokenData.idToken = oldTokenData!.idToken
}
}
// Update storage
self.tokenStorage.saveTokens(newTokenData: newTokenData)
}
/*
* Return true if this is a user cancellation error that can be ignored and not the value from the below issue
* https://github.com/openid/AppAuth-iOS/issues/498
*/
private func isCancelledError(error: Error) -> Bool {
let authError = error as NSError
return self.matchesAppAuthError(
error: error,
domain: OIDGeneralErrorDomain,
code: OIDErrorCode.userCanceledAuthorizationFlow.rawValue) &&
!authError.userInfo.description.localizedStandardContains("active state")
}
/*
* Return true if this is a logout state mismatch error that is expected and can be ignored
*/
private func isLogoutStateMismatchError(error: Error) -> Bool {
let authError = error as NSError
return self.matchesAppAuthError(
error: error,
domain: OIDOAuthAuthorizationErrorDomain,
code: OIDErrorCodeOAuth.clientError.rawValue) &&
authError.userInfo.description.localizedStandardContains("State mismatch")
}
/*
* Check for a particular AppAuth error
*/
private func matchesAppAuthError(error: Error, domain: String, code: Int) -> Bool {
let authError = error as NSError
return authError.domain == domain && authError.code == code
}
/*
* Return the URL to the interstitial page used for login redirects
* https://authsamples.com/apps/basicmobileapp/postlogin.html
*/
private func getLoginRedirectUri() -> String {
return "\(self.configuration.webBaseUrl)\(self.configuration.loginRedirectPath)"
}
/*
* Return the URL to the interstitial page used for logout redirects
* https://authsamples.com/apps/basicmobileapp/postlogout.html
*/
private func getPostLogoutRedirectUri() -> String {
return "\(self.configuration.webBaseUrl)\(self.configuration.postLogoutRedirectPath)"
}
/*
* Return the deep linking app location that the interstitial page invokes after login
* https://mobile.authsamples.com/basicmobileapp/oauth/callback
*/
private func getLoginReactivateUri() -> String {
return "\(self.configuration.deepLinkBaseUrl)\(self.configuration.loginActivatePath)"
}
/*
* Return the deep linking app location that the interstitial page invokes after logout
* https://mobile.authsamples.com/basicmobileapp/oauth/logoutcallback
*/
private func getPostLogoutReactivateUri() -> String {
return "\(self.configuration.deepLinkBaseUrl)\(self.configuration.postLogoutActivatePath)"
}
/*
* Return the logout manager for the active provider
*/
private func createLogoutManager() -> LogoutManager {
if self.configuration.authority.lowercased().contains("cognito") {
return CognitoLogoutManager(configuration: self.configuration)
} else {
return StandardLogoutManager(configuration: self.configuration)
}
}
}
// swiftlint:enable type_body_length