Skip to content

Commit

Permalink
fix token refreshing
Browse files Browse the repository at this point in the history
  • Loading branch information
llbartekll committed Nov 7, 2024
1 parent 397eead commit c0f5748
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,28 @@ public protocol ClientIdAuthenticating {

public final class ClientIdAuthenticator: ClientIdAuthenticating {
private let clientIdStorage: ClientIdStoring
private let logger: ConsoleLogging

public init(clientIdStorage: ClientIdStoring) {
public init(clientIdStorage: ClientIdStoring,
logger: ConsoleLogging) {
self.clientIdStorage = clientIdStorage
self.logger = logger
}

public func createAuthToken(url: String) throws -> String {
let keyPair = try clientIdStorage.getOrCreateKeyPair()
let payload = RelayAuthPayload(subject: getSubject(), audience: url)
logger.debug("Creating auth token for \(url)")
return try payload.signAndCreateWrapper(keyPair: keyPair).jwtString
}

public func refreshTokenIfNeeded(token: String, url: String) throws -> String {
if try isTokenExpired(token: token) {
logger.debug("Refreshing auth token for \(url)")
// Token has expired, generate a new one
return try createAuthToken(url: url)
} else {
logger.debug("Token is still valid for \(url)")
// Token is still valid, return existing token
return token
}
Expand Down
3 changes: 2 additions & 1 deletion Sources/WalletConnectRelay/RelayClientFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ public struct RelayClientFactory {
let clientIdStorage = ClientIdStorage(defaults: keyValueStorage, keychain: keychainStorage, logger: logger)

let socketAuthenticator = ClientIdAuthenticator(
clientIdStorage: clientIdStorage
clientIdStorage: clientIdStorage,
logger: logger
)
let relayUrlFactory = RelayUrlFactory(
relayHost: relayHost,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,13 @@ class AutomaticSocketConnectionHandler {
}

do {
let refreshedToken = try clientIdAuthenticator.refreshTokenIfNeeded(token: token, url: socket.request.url!.absoluteString)
// Parse the URL and extract only the base URL (without query parameters)
var urlComponents = URLComponents(url: socket.request.url!, resolvingAgainstBaseURL: false)
urlComponents?.query = nil
let baseUrlString = urlComponents?.url?.absoluteString ?? socket.request.url!.absoluteString

// Refresh the token with just the base URL
let refreshedToken = try clientIdAuthenticator.refreshTokenIfNeeded(token: token, url: baseUrlString)
let newAuthorizationHeader = "Bearer \(refreshedToken)"
socket.request.allHTTPHeaderFields?["Authorization"] = newAuthorizationHeader
} catch {
Expand Down

0 comments on commit c0f5748

Please sign in to comment.