-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Authorization Refresh #3
Merged
+215
−87
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
133 changes: 133 additions & 0 deletions
133
Sources/AppleMapsKit/Authorization/AuthorizationProvider.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
// | ||
// AuthorizationProvider.swift | ||
// apple-maps-kit | ||
// | ||
// Created by FarouK on 11/10/2024. | ||
// | ||
|
||
import AsyncHTTPClient | ||
import Foundation | ||
import JWTKit | ||
import NIOHTTP1 | ||
|
||
// MARK: - auth/c & auth/z | ||
internal actor AuthorizationProvider { | ||
|
||
private let httpClient: HTTPClient | ||
private let apiServer: String | ||
private let teamID: String | ||
private let keyID: String | ||
private let key: String | ||
|
||
private var currentToken: TokenResponse? | ||
private var refreshTask: Task<TokenResponse, any Error>? | ||
|
||
internal init(httpClient: HTTPClient, apiServer: String, teamID: String, keyID: String, key: String) { | ||
self.httpClient = httpClient | ||
self.apiServer = apiServer | ||
self.teamID = teamID | ||
self.keyID = keyID | ||
self.key = key | ||
} | ||
|
||
func validToken() async throws -> TokenResponse { | ||
// If we're currently refreshing a token, await the value for our refresh task to make sure we return the refreshed token. | ||
if let handle = refreshTask { | ||
return try await handle.value | ||
} | ||
|
||
// If we don't have a current token, we request a new one. | ||
guard let token = currentToken else { | ||
return try await refreshToken() | ||
} | ||
|
||
if token.isValid { | ||
return token | ||
} | ||
|
||
// None of the above applies so we'll need to refresh the token. | ||
return try await refreshToken() | ||
} | ||
|
||
private func refreshToken() async throws -> TokenResponse { | ||
if let refreshTask = refreshTask { | ||
return try await refreshTask.value | ||
} | ||
|
||
let task = Task { () throws -> TokenResponse in | ||
defer { refreshTask = nil } | ||
let authToken = try await createJWT(teamID: teamID, keyID: keyID, key: key) | ||
let newToken = try await getAccessToken(authToken: authToken) | ||
currentToken = newToken | ||
return newToken | ||
} | ||
|
||
self.refreshTask = task | ||
return try await task.value | ||
} | ||
} | ||
|
||
// MARK: - HELPERS | ||
extension AuthorizationProvider { | ||
|
||
/// Makes an HTTP request to exchange Auth token for Access token. | ||
/// | ||
/// - Parameters: | ||
/// - httpClient: The HTTP client to use. | ||
/// - authToken: The authorization token. | ||
/// | ||
/// - Throws: Error response object. | ||
/// | ||
/// - Returns: An access token. | ||
fileprivate func getAccessToken(authToken: String) async throws -> TokenResponse { | ||
var headers = HTTPHeaders() | ||
headers.add(name: "Authorization", value: "Bearer \(authToken)") | ||
|
||
var request = HTTPClientRequest(url: "\(apiServer)/v1/token") | ||
request.headers = headers | ||
|
||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
|
||
if response.status == .ok { | ||
return try await JSONDecoder() | ||
.decode(TokenResponse.self, from: response.body.collect(upTo: 1024 * 1024)) | ||
} else { | ||
throw try await JSONDecoder().decode(ErrorResponse.self, from: response.body.collect(upTo: 1024 * 1024)) | ||
} | ||
} | ||
|
||
/// Creates a JWT token, which is auth token in this context. | ||
/// | ||
/// - Parameters: | ||
/// - teamID: A 10-character Team ID obtained from your Apple Developer account. | ||
/// - keyID: A 10-character key identifier that provides the ID of the private key that you obtain from your Apple Developer account. | ||
/// - key: A MapKit JS private key. | ||
/// | ||
/// - Returns: A JWT token represented as `String`. | ||
fileprivate func createJWT(teamID: String, keyID: String, key: String) async throws -> String { | ||
let keys = try await JWTKeyCollection().add(ecdsa: ES256PrivateKey(pem: key)) | ||
|
||
var header = JWTHeader() | ||
header.alg = "ES256" | ||
header.kid = keyID | ||
header.typ = "JWT" | ||
|
||
struct Payload: JWTPayload { | ||
let iss: IssuerClaim | ||
let iat: IssuedAtClaim | ||
let exp: ExpirationClaim | ||
|
||
func verify(using key: some JWTAlgorithm) throws { | ||
try self.exp.verifyNotExpired() | ||
} | ||
} | ||
|
||
let payload = Payload( | ||
iss: IssuerClaim(value: teamID), | ||
iat: IssuedAtClaim(value: Date()), | ||
exp: ExpirationClaim(value: Date().addingTimeInterval(30 * 60)) | ||
) | ||
|
||
return try await keys.sign(payload, header: header) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import Foundation | ||
|
||
/// An object that contains an access token and an expiration time in seconds. | ||
internal struct TokenResponse: Codable { | ||
/// A string that represents the access token. | ||
let accessToken: String | ||
|
||
/// An integer that indicates the time, in seconds from now until the token expires. | ||
let expiresInSeconds: Int | ||
|
||
/// A date that indicates when then token will expire. | ||
let expirationDate: Date | ||
|
||
internal init(from decoder: any Decoder) throws { | ||
let container = try decoder.container(keyedBy: CodingKeys.self) | ||
self.accessToken = try container.decode(String.self, forKey: .accessToken) | ||
self.expiresInSeconds = try container.decode(Int.self, forKey: .expiresInSeconds) | ||
self.expirationDate = Date.now.addingTimeInterval(TimeInterval(expiresInSeconds)) | ||
} | ||
|
||
internal init(accessToken: String, expiresInSeconds: Int) { | ||
self.accessToken = accessToken | ||
self.expiresInSeconds = expiresInSeconds | ||
self.expirationDate = Date.now.addingTimeInterval(TimeInterval(expiresInSeconds)) | ||
} | ||
|
||
} | ||
|
||
extension TokenResponse { | ||
|
||
/// A boolean indicates whether to token is valid 10 seconds before it's actual expiry time. | ||
var isValid: Bool { | ||
let currentDate = Date.now | ||
// we consider a token invalid 10 seconds before it actual expiry time, so we have some time to refresh it. | ||
let expirationBuffer: TimeInterval = 10 | ||
return currentDate < (expirationDate - expirationBuffer) | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// | ||
// AuthorizationProviderTests.swift | ||
// apple-maps-kit | ||
// | ||
// Created by FarouK on 12/10/2024. | ||
// | ||
|
||
import Testing | ||
|
||
@testable import AppleMapsKit | ||
|
||
struct AuthorizationProviderTests { | ||
|
||
struct TokenValidityTests { | ||
// It's 1 second actually due to the expiration buffer on the token. | ||
let token = TokenResponse(accessToken: "some token", expiresInSeconds: 11) | ||
|
||
@Test func tokenInvalidCheck() async { | ||
try? await Task.sleep(for: .seconds(2)) | ||
#expect(token.isValid == false) | ||
} | ||
|
||
@Test func tokenValidCheck() async { | ||
#expect(token.isValid) | ||
} | ||
} | ||
|
||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this doesn't ever become false, as the
Date.now
is new every time andexpiresInSeconds
doesn't get updated since the response is received.Maybe we can add a private
expirationDate
property toTokenResponse
to which we assignDate.now.addingTimeInterval(TimeInterval(expiresInSeconds))
when theTokenResponse
gets initializedThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes it's a very good point, sorry for that.
I will push a fix and write a test for it.