-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathToken.swift
More file actions
318 lines (273 loc) · 11.8 KB
/
Copy pathToken.swift
File metadata and controls
318 lines (273 loc) · 11.8 KB
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
//
// Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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
#if !COCOAPODS
import CommonSupport
@_exported import JSON
#endif
/// Token information representing a user's access to a resource server, including access token, refresh token, and other related information.
public struct Token: Sendable, Codable, Equatable, Hashable, HasClaims, Expires {
public typealias ClaimType = TokenClaim
/// The object used to ensure ID tokens are valid.
public static var idTokenValidator: any IDTokenValidator {
get {
lock.withLock { _idTokenValidator }
}
set {
lock.withLock { _idTokenValidator = newValue }
}
}
/// The object used to ensure access tokens can be validated against its associated ID token.
public static var accessTokenValidator: any TokenHashValidator {
get {
lock.withLock { _accessTokenValidator }
}
set {
lock.withLock { _accessTokenValidator = newValue }
}
}
/// The object used to ensure device secrets are validated against its associated ID token.
public static var deviceSecretValidator: any TokenHashValidator {
get {
lock.withLock { _deviceSecretValidator }
}
set {
lock.withLock { _deviceSecretValidator = newValue }
}
}
/// Coordinates important operations during token exchange.
///
/// > Note: This property and interface is currently marked as internal, but may be exposed publicly in the future.
static var exchangeCoordinator: any TokenExchangeCoordinator {
get {
lock.withLock { _exchangeCoordinator }
}
set {
lock.withLock { _exchangeCoordinator = newValue }
}
}
/// The unique identifier for this token.
public let id: String
/// The date this token was issued at.
public let issuedAt: Date?
/// The string type of the token (e.g. `Bearer`).
public let tokenType: String
/// The expiration duration for this token.
public let expiresIn: TimeInterval
/// Access token.
public let accessToken: String
/// The scopes requested when this token was generated.
public var scope: [String]? { self[.scope] }
/// The refresh token, if requested.
public var refreshToken: String? { self[.refreshToken] }
/// The ID token, if requested.
///
/// For more information on working with an ID token, see ``HasClaims`` for more.
public let idToken: JWT?
/// Defines the context this token was issued from.
public let context: Context
/// The Device secret, if requested in scope.
public var deviceSecret: String? { self[.deviceSecret] }
/// The type of token issued to the client when using Token Exchange Flow.
public var issuedTokenType: String? { self[.issuedTokenType] }
/// The claim payload container for this token
@_documentation(visibility: internal)
public var payload: [String: any Sendable] { json.payload }
/// Indicates whether or not the token is being refreshed.
public var isRefreshing: Bool {
refreshAction.isActive
}
public let json: JSON
internal let refreshAction: CoalescedResult<Token>
/// Return the relevant token string for the given type.
/// - Parameter kind: Type of token string to return
/// - Returns: Token string, or `nil` if this token doesn't contain the requested type.
public func token(of kind: Kind) -> String? {
switch kind {
case .accessToken:
return accessToken
case .refreshToken:
return refreshToken
case .idToken:
return idToken?.rawValue
case .deviceSecret:
return deviceSecret
}
}
/// Validates the claims within this JWT token, to ensure it matches the given ``OAuth2Client``.
/// - Parameters:
/// - client: Client to validate the token's claims against.
/// - context: Optional ``AuthenticationContext`` to use when validating the token.
public func validate(using client: OAuth2Client, with context: any AuthenticationContext) async throws {
guard let idToken = idToken else {
return
}
let issuer = try await client.openIdConfiguration().issuer
try Token.idTokenValidator.validate(token: idToken,
issuer: issuer,
clientId: client.configuration.clientId,
context: context)
try Token.accessTokenValidator.validate(accessToken, idToken: idToken)
if let deviceSecret = deviceSecret {
try Token.deviceSecretValidator.validate(deviceSecret, idToken: idToken)
}
}
/// Creates a new Token from a refresh token.
/// - Parameters:
/// - refreshToken: Refresh token string.
/// - scope: Optional array of scopes to request.
/// - client: ``OAuth2Client`` instance that corresponds to the client configuration initially used to create the refresh token.
public static func from(refreshToken: String,
scope: [String]? = nil,
using client: OAuth2Client) async throws -> Token
{
let request = Token.RefreshRequest(openIdConfiguration: try await client.openIdConfiguration(),
clientConfiguration: client.configuration,
refreshToken: refreshToken,
scope: scope?.joined(separator: " "),
id: Token.RefreshRequest.placeholderId)
let response = try await client.exchange(token: request)
TaskData.notificationCenter.post(name: .tokenRefreshed, object: response.result)
return response.result
}
@_documentation(visibility: private)
public static let jsonDecoder = JSONDecoder()
public static func == (lhs: Token, rhs: Token) -> Bool {
lhs.context == rhs.context &&
lhs.accessToken == rhs.accessToken &&
lhs.refreshToken == rhs.refreshToken &&
lhs.scope == rhs.scope &&
lhs.idToken?.rawValue == rhs.idToken?.rawValue &&
lhs.deviceSecret == rhs.deviceSecret
}
public func hash(into hasher: inout Hasher) {
hasher.combine(context)
hasher.combine(accessToken)
hasher.combine(scope)
hasher.combine(idToken?.rawValue)
hasher.combine(deviceSecret)
}
init(id: String,
issuedAt: Date,
context: Context,
json: JSON) throws
{
self.id = id
self.issuedAt = issuedAt
self.context = context
self.json = json
self.refreshAction = .init(taskName: "Refresh Token \(id)")
if let value = json[TokenClaim.idToken.rawValue]?.string {
idToken = try JWT(value)
} else {
idToken = nil
}
// Ensure an access token is provided.
if let value: String = TokenClaim.optionalValue(.accessToken, in: json.payload) {
accessToken = value
}
// When the custom MFA attestation ACR value is used, allow for
// an empty / unspecified access token.
else if let acrValues = context.clientSettings?["acr_values"]?.whitespaceSeparated,
acrValues.contains("urn:okta:app:mfa:attestation")
{
accessToken = ""
}
// Throw an error when no access token is available.
else {
throw ClaimError.missingRequiredValue(key: TokenClaim.accessToken.rawValue)
}
tokenType = try TokenClaim.value(.tokenType, in: json.payload)
expiresIn = try TokenClaim.value(.expiresIn, in: json.payload)
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeysV2.self)
try container.encode(id, forKey: .id)
try container.encodeIfPresent(issuedAt, forKey: .issuedAt)
try container.encode(context, forKey: .context)
try container.encode(json, forKey: .rawValue)
}
// MARK: Private properties / methods
private static let lock = Lock()
nonisolated(unsafe) private static var _idTokenValidator: any IDTokenValidator = DefaultIDTokenValidator()
nonisolated(unsafe) private static var _accessTokenValidator: any TokenHashValidator = DefaultTokenHashValidator(hashKey: .accessToken)
nonisolated(unsafe) private static var _deviceSecretValidator: any TokenHashValidator = DefaultTokenHashValidator(hashKey: .deviceSecret)
nonisolated(unsafe) private static var _exchangeCoordinator: any TokenExchangeCoordinator = DefaultTokenExchangeCoordinator()
}
extension Token {
/// Creates a new Token from a refresh token.
/// - Parameters:
/// - refreshToken: Refresh token string.
/// - scope: Optional array of scopes to request.
/// - client: ``OAuth2Client`` instance that corresponds to the client configuration initially used to create the refresh token.
/// - completion: Completion block invoked when a result is returned.
public static func from(refreshToken: String,
scope: [String]? = nil,
using client: OAuth2Client,
completion: @Sendable @escaping (Result<Token, OAuth2Error>) -> Void)
{
Task {
do {
completion(.success(try await from(refreshToken: refreshToken,
scope: scope,
using: client)))
} catch {
completion(.failure(OAuth2Error(error)))
}
}
}
}
extension Token {
enum CodingKeysV1: String, CodingKey, CaseIterable {
case id
case issuedAt
case tokenType
case expiresIn
case accessToken
case scope
case refreshToken
case idToken
case deviceSecret
case context
}
enum CodingKeysV2: String, CodingKey, CaseIterable {
case id
case issuedAt
case context
case rawValue
}
}
@_documentation(visibility: private)
extension CodingUserInfoKey {
// swiftlint:disable force_unwrapping
public static let tokenId = CodingUserInfoKey(rawValue: "tokenId")!
public static let apiClientConfiguration = CodingUserInfoKey(rawValue: "apiClientConfiguration")!
public static let tokenContext = CodingUserInfoKey(rawValue: "tokenContext")!
public static let clientSettings = CodingUserInfoKey(rawValue: "clientSettings")!
// swiftlint:enable force_unwrapping
}
extension Token {
public enum TokenClaim: String, IsClaim, CaseIterable {
// Core OAuth 2.0 (RFC 6749)
case accessToken = "access_token"
case tokenType = "token_type"
case expiresIn = "expires_in"
case refreshToken = "refresh_token"
case scope
// OpenID Connect (OIDC)
case idToken = "id_token"
// OAuth 2.0 Token Exchange (RFC 8693)
case issuedTokenType = "issued_token_type"
// OpenID Connect Native SSO for Mobile Apps 1.0
case deviceSecret = "device_secret"
}
}