-
Notifications
You must be signed in to change notification settings - Fork 85
/
TrustedPersistantOAuth2Session.swift
386 lines (340 loc) · 14 KB
/
TrustedPersistantOAuth2Session.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
/*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import Security
import UIKit
/**
The type of token to be saved in KeychainWrap:
- AccessToken: access token
- ExpirationDate: access token expiration date
- RefreshToken: refresh token
- RefreshExpirationDate: refresh token expiration date (used for Keycloak adapter only)
*/
public enum TokenType: String {
case AccessToken = "AccessToken"
case RefreshToken = "RefreshToken"
case ExpirationDate = "ExpirationDate"
case RefreshExpirationDate = "RefreshExpirationDate"
case IdToken = "IdToken"
}
/**
A handy Keychain wrapper. It saves your OAuth2 tokens using WhenPasscodeSet ACL.
*/
public class KeychainWrap {
/**
The service id. By default set to apple bundle id.
*/
public var serviceIdentifier: String
/**
The group id is Keychain access group which is used for sharing keychain content across multiple apps issued from same developer. By default there is no access group.
*/
public var groupId: String?
/**
Initialize KeychainWrapper setting default values.
:param: serviceId unique service, defaulted to bundleId
:param: groupId used for SSO between app issued from same developer certificate.
*/
public init(serviceId: String? = Bundle.main.bundleIdentifier, groupId: String? = nil) {
if serviceId == nil {
self.serviceIdentifier = "unknown"
} else {
self.serviceIdentifier = serviceId!
}
self.groupId = groupId
}
/**
Save tokens information in Keychain.
:param: key usually use accountId for OAuth2 module, any unique string.
:param: tokenType type of token: access, refresh.
:param: value string value of the token.
*/
public func save(key: String, tokenType: TokenType, value: String) -> Bool {
let dataFromString: Data? = value.data(using: String.Encoding.utf8)
if (dataFromString == nil) {
return false
}
// Instantiate a new default keychain query
let keychainQuery = NSMutableDictionary()
if let groupId = self.groupId {
keychainQuery[kSecAttrAccessGroup as String] = groupId
}
keychainQuery[kSecClass as String] = kSecClassGenericPassword
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
keychainQuery[kSecAttrAccount as String] = key + "_" + tokenType.rawValue
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
// Search for the keychain items
let statusSearch: OSStatus = SecItemCopyMatching(keychainQuery, nil)
// if found update
if (statusSearch == errSecSuccess) {
if (dataFromString != nil) {
let attributesToUpdate = NSMutableDictionary()
attributesToUpdate[kSecValueData as String] = dataFromString!
let statusUpdate: OSStatus = SecItemUpdate(keychainQuery, attributesToUpdate)
if (statusUpdate != errSecSuccess) {
print("tokens not updated")
return false
}
} else { // revoked token or newly installed app, clear KC
return self.resetKeychain()
}
} else if(statusSearch == errSecItemNotFound) { // if new, add
keychainQuery[kSecValueData as String] = dataFromString!
let statusAdd: OSStatus = SecItemAdd(keychainQuery, nil)
if(statusAdd != errSecSuccess) {
print("tokens not saved")
return false
}
} else { // error case
return false
}
return true
}
/**
Delete a specific token in Keychain.
:param: key usually use accountId for oauth2 module, any unique string.
:param: tokenType type of token.
*/
public func delete(key: String, tokenType: TokenType) -> Bool {
let keychainQuery = NSMutableDictionary()
if let groupId = self.groupId {
keychainQuery[kSecAttrAccessGroup as String] = groupId
}
keychainQuery[kSecClass as String] = kSecClassGenericPassword
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
keychainQuery[kSecAttrAccount as String] = key + "_" + tokenType.rawValue
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
let statusDelete: OSStatus = SecItemDelete(keychainQuery)
return statusDelete == noErr
}
/**
Read tokens information in Keychain. If the entry is not found return nil.
:param: userAccount key of the keychain entry, usually accountId for oauth2 module.
:param: tokenType type of token: access, refresh.
*/
public func read(userAccount: String, tokenType: TokenType) -> String? {
let keychainQuery = NSMutableDictionary()
if let groupId = self.groupId {
keychainQuery[kSecAttrAccessGroup as String] = groupId
}
keychainQuery[kSecClass as String] = kSecClassGenericPassword
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
keychainQuery[kSecAttrAccount as String] = userAccount + "_" + tokenType.rawValue
keychainQuery[kSecMatchLimit as String] = kSecMatchLimitOne
keychainQuery[kSecReturnData as String] = kCFBooleanTrue
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
var dataTypeRef: AnyObject?
// Search for the keychain items
let status: OSStatus = withUnsafeMutablePointer(to: &dataTypeRef) {
SecItemCopyMatching(keychainQuery as CFDictionary, UnsafeMutablePointer($0))
}
if (status == errSecItemNotFound) {
print("\(tokenType.rawValue) not found")
return nil
} else if (status != errSecSuccess) {
print("Error attempting to retrieve \(tokenType.rawValue) with error code \(status) ")
return nil
}
guard let keychainData = dataTypeRef as? Data else {
return nil
}
return String(data: keychainData, encoding: String.Encoding.utf8) as String?
}
/**
Clear all keychain entries. Note that Keychain can only be cleared programmatically.
*/
public func resetKeychain() -> Bool {
return self.deleteAllKeysForSecClass(secClass: kSecClassGenericPassword) &&
self.deleteAllKeysForSecClass(secClass: kSecClassInternetPassword) &&
self.deleteAllKeysForSecClass(secClass: kSecClassCertificate) &&
self.deleteAllKeysForSecClass(secClass: kSecClassKey) &&
self.deleteAllKeysForSecClass(secClass: kSecClassIdentity)
}
func deleteAllKeysForSecClass(secClass: CFTypeRef) -> Bool {
let keychainQuery = NSMutableDictionary()
keychainQuery[kSecClass as String] = secClass
let result: OSStatus = SecItemDelete(keychainQuery)
if (result == errSecSuccess) {
return true
} else {
return false
}
}
}
/**
An OAuth2Session implementation to store OAuth2 metadata using the Keychain.
*/
public class TrustedPersistentOAuth2Session: OAuth2Session {
/**
The account id.
*/
public var accountId: String
/**
The access token's expiration date.
*/
public var accessTokenExpirationDate: Date? {
get {
let dateAsString = self.keychain.read(userAccount: self.accountId, tokenType: .ExpirationDate)
if let unwrappedDate: String = dateAsString {
return Date(dateString: unwrappedDate) as Date?
} else {
return nil
}
}
set(value) {
if let unwrappedValue = value {
_ = self.keychain.save(key: self.accountId, tokenType: .ExpirationDate, value: unwrappedValue.toString())
} else {
_ = self.keychain.delete(key: self.accountId, tokenType: .ExpirationDate)
}
}
}
/**
The access token. The information is read securely from Keychain.
*/
public var accessToken: String? {
get {
return self.keychain.read(userAccount: self.accountId, tokenType: .AccessToken)
}
set(value) {
if let unwrappedValue = value {
_ = self.keychain.save(key: self.accountId, tokenType: .AccessToken, value: unwrappedValue)
} else {
_ = self.keychain.delete(key: self.accountId, tokenType: .AccessToken)
}
}
}
/**
The refresh token. The information is read securely from Keychain.
*/
public var refreshToken: String? {
get {
return self.keychain.read(userAccount: self.accountId, tokenType: .RefreshToken)
}
set(value) {
if let unwrappedValue = value {
_ = self.keychain.save(key: self.accountId, tokenType: .RefreshToken, value: unwrappedValue)
} else {
_ = self.keychain.delete(key: self.accountId, tokenType: .RefreshToken)
}
}
}
/**
The refresh token's expiration date.
*/
public var refreshTokenExpirationDate: Date? {
get {
let dateAsString = self.keychain.read(userAccount: self.accountId, tokenType: .RefreshExpirationDate)
if let unwrappedDate: String = dateAsString {
return Date(dateString: unwrappedDate)
} else {
return nil
}
}
set(value) {
if let unwrappedValue = value {
_ = self.keychain.save(key: self.accountId, tokenType: .RefreshExpirationDate, value: unwrappedValue.toString())
} else {
_ = self.keychain.delete(key: self.accountId, tokenType: .RefreshExpirationDate)
}
}
}
/**
The JWT. The information is read securely from Keychain.
*/
public var idToken: String? {
get {
return self.keychain.read(userAccount: self.accountId, tokenType: .IdToken)
}
set(value) {
if let unwrappedValue = value {
_ = self.keychain.save(key: self.accountId, tokenType: .IdToken, value: unwrappedValue)
}
}
}
private let keychain: KeychainWrap
/**
Check validity of accessToken. return true if still valid, false when expired.
*/
public func tokenIsNotExpired() -> Bool {
return self.accessTokenExpirationDate != nil ? (self.accessTokenExpirationDate!.timeIntervalSince(Date()) > 0) : true
}
/**
Check validity of refreshToken. return true if still valid, false when expired.
*/
public func refreshTokenIsNotExpired() -> Bool {
return self.refreshTokenExpirationDate != nil ? (self.refreshTokenExpirationDate!.timeIntervalSince(Date()) > 0) : true
}
/**
Save in memory tokens information. Saving tokens allow you to refresh accesstoken transparently for the user without prompting for grant access.
*/
public func save(accessToken: String?, refreshToken: String?, accessTokenExpiration: String?, refreshTokenExpiration: String?, idToken: String?) {
self.accessToken = accessToken
self.refreshToken = refreshToken
self.idToken = idToken
let now = Date()
if let inter = accessTokenExpiration?.doubleValue {
self.accessTokenExpirationDate = now.addingTimeInterval(inter)
}
if let inter = refreshTokenExpiration?.doubleValue {
self.refreshTokenExpirationDate = now.addingTimeInterval(inter)
}
}
/**
Clear all tokens. Method used when doing logout or revoke.
*/
public func clearTokens() {
self.accessToken = nil
self.refreshToken = nil
self.accessTokenExpirationDate = nil
self.refreshTokenExpirationDate = nil
self.idToken = nil
}
/**
Initialize TrustedPersistentOAuth2Session using account id. Account id is the service id used for keychain storage.
:param: accountId uniqueId to identify the OAuth2Module
:param: groupId used for SSO between app issued from same developer certificate.
:param: accessToken optional parameter to initialize the storage with initial values
:param: accessTokenExpirationDate optional parameter to initialize the storage with initial values
:param: refreshToken optional parameter to initialize the storage with initial values
:param: refreshTokenExpirationDate optional parameter to initialize the storage with initial values
*/
public init(accountId: String,
groupId: String? = nil,
accessToken: String? = nil,
accessTokenExpirationDate: Date? = nil,
refreshToken: String? = nil,
refreshTokenExpirationDate: Date? = nil) {
self.accountId = accountId
if groupId != nil {
self.keychain = KeychainWrap(serviceId: groupId, groupId: groupId)
} else {
self.keychain = KeychainWrap()
}
if accessToken != nil {
self.accessToken = accessToken
}
if refreshToken != nil {
self.refreshToken = refreshToken
}
if accessToken != nil && accessTokenExpirationDate != nil {
self.accessTokenExpirationDate = accessTokenExpirationDate as Date?
}
if refreshToken != nil && refreshTokenExpirationDate != nil {
self.refreshTokenExpirationDate = refreshTokenExpirationDate
}
}
}