How to synchronously refresh an access token using Alamofire + RxSwift - swift

I have this generic fetchData() function in my NetworkManager class that is able to request make a authorised request to the network and if it fail (after a number of retries) emits an error that will restart my app (requesting a new login). I need that this retry token be called synchronously, I mean, if multiple requests failed, only one should be requesting the refresh token at once. And if that one fail, and the other one requests must be discarded. I already tried some approached using DispatchGroup / NSRecursiveLock / and also with calling the function cancelRequests describing bellow (in this case, the tasks count is always 0). How can I make this behaviour works in this scenario?
My NetworkManager class:
public func fetchData<Type: Decodable>(fromApi api: TargetType,
decodeFromKeyPath keyPath: String? = nil) -> Single<Response> {
let request = MultiTarget(api)
return provider.rx.request(request)
.asRetriableAuthenticated(target: request)
}
func cancelAllRequests(){
if #available(iOS 9.0, *) {
DefaultAlamofireManager
.sharedManager
.session
.getAllTasks { (tasks) in
tasks.forEach{ $0.cancel() }
}
} else {
DefaultAlamofireManager
.sharedManager
.session
.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
sessionDataTask.forEach { $0.cancel() }
uploadData.forEach { $0.cancel() }
downloadData.forEach { $0.cancel() }
}
}
}
The Single extension that make the retry works:
public extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
private var refreshTokenParameters: TokenParameters {
TokenParameters(clientId: "pdappclient",
grantType: "refresh_token",
refreshToken: KeychainManager.shared.refreshToken)
}
func retryWithToken(target: MultiTarget) -> Single<E> {
self.catchError { error -> Single<Response> in
if case Moya.MoyaError.statusCode(let response) = error {
if self.isTokenExpiredError(error) {
return Single.error(error)
} else {
return self.parseError(response: response)
}
}
return Single.error(error)
}
.retryToken(target: target)
.catchError { error -> Single<Response> in
if case Moya.MoyaError.statusCode(let response) = error {
return self.parseError(response: response)
}
return Single.error(InvalidGrantException())
}
}
private func retryToken(target: MultiTarget) -> Single<E> {
let maxRetries = 1
return self.retryWhen({ error in
error
.enumerated()
.flatMap { (attempt, error) -> Observable<Int> in
if attempt >= maxRetries {
return Observable.error(error)
}
if self.isTokenExpiredError(error) {
return Observable<Int>.just(attempt + 1)
}
return Observable.error(error)
}
.flatMap { _ -> Single<TokenResponse> in
self.refreshTokenRequest()
}
.share()
.asObservable()
})
}
private func refreshTokenRequest() -> Single<TokenResponse> {
return NetworkManager.shared.fetchData(fromApi: IdentityServerAPI
.token(parameters: self.refreshTokenParameters)).do(onSuccess: { tokenResponse in
KeychainManager.shared.accessToken = tokenResponse.accessToken
KeychainManager.shared.refreshToken = tokenResponse.refreshToken
}, onError: { error in
NetworkManager.shared.cancelAllRequests()
})
}
func parseError<E>(response: Response) -> Single<E> {
if response.statusCode == 401 {
// TODO
}
let decoder = JSONDecoder()
if let errors = try? response.map([BaseResponseError].self, atKeyPath: "errors", using: decoder,
failsOnEmptyData: true) {
return Single.error(BaseAPIErrorResponse(errors: errors))
}
return Single.error(APIError2.unknown)
}
func isTokenExpiredError(_ error: Error) -> Bool {
if let moyaError = error as? MoyaError {
switch moyaError {
case .statusCode(let response):
if response.statusCode != 401 {
return false
} else if response.data.count == 0 {
return true
}
default:
break
}
}
return false
}
func filterUnauthorized() -> Single<E> {
flatMap { (response) -> Single<E> in
if 200...299 ~= response.statusCode {
return Single.just(response)
} else if response.statusCode == 404 {
return Single.just(response)
} else {
return Single.error(MoyaError.statusCode(response))
}
}
}
func asRetriableAuthenticated(target: MultiTarget) -> Single<Element> {
filterUnauthorized()
.retryWithToken(target: target)
.filterStatusCode()
}
func filterStatusCode() -> Single<E> {
flatMap { (response) -> Single<E> in
if 200...299 ~= response.statusCode {
return Single.just(response)
} else {
return self.parseError(response: response)
}
}
}
}

Here is an RxSwift solution: RxSwift and Handling Invalid Tokens
Just posting the link isn't the best, so I will post the core of the solution as well:
The key is to make a class that is much like the ActivityMonitor class but handles token refreshing...
public final class TokenAcquisitionService<T> {
/// responds with the current token immediatly and emits a new token whenver a new one is aquired. You can, for example, subscribe to it in order to save the token as it's updated.
public var token: Observable<T> {
return _token.asObservable()
}
public typealias GetToken = (T) -> Observable<(response: HTTPURLResponse, data: Data)>
/// Creates a `TokenAcquisitionService` object that will store the most recent authorization token acquired and will acquire new ones as needed.
///
/// - Parameters:
/// - initialToken: The token the service should start with. Provide a token from storage or an empty string (object represting a missing token) if one has not been aquired yet.
/// - getToken: A function responsable for aquiring new tokens when needed.
/// - extractToken: A function that can extract a token from the data returned by `getToken`.
public init(initialToken: T, getToken: #escaping GetToken, extractToken: #escaping (Data) throws -> T) {
relay
.flatMapFirst { getToken($0) }
.map { (urlResponse) -> T in
guard urlResponse.response.statusCode / 100 == 2 else { throw TokenAcquisitionError.refusedToken(response: urlResponse.response, data: urlResponse.data) }
return try extractToken(urlResponse.data)
}
.startWith(initialToken)
.subscribe(_token)
.disposed(by: disposeBag)
}
/// Allows the token to be set imperativly if necessary.
/// - Parameter token: The new token the service should use. It will immediatly be emitted to any subscribers to the service.
func setToken(_ token: T) {
lock.lock()
_token.onNext(token)
lock.unlock()
}
/// Monitors the source for `.unauthorized` error events and passes all other errors on. When an `.unauthorized` error is seen, `self` will get a new token and emit a signal that it's safe to retry the request.
///
/// - Parameter source: An `Observable` (or like type) that emits errors.
/// - Returns: A trigger that will emit when it's safe to retry the request.
func trackErrors<O: ObservableConvertibleType>(for source: O) -> Observable<Void> where O.Element == Error {
let lock = self.lock
let relay = self.relay
let error = source
.asObservable()
.map { error in
guard (error as? TokenAcquisitionError) == .unauthorized else { throw error }
}
.flatMap { [unowned self] in self.token }
.do(onNext: {
lock.lock()
relay.onNext($0)
lock.unlock()
})
.filter { _ in false }
.map { _ in }
return Observable.merge(token.skip(1).map { _ in }, error)
}
private let _token = ReplaySubject<T>.create(bufferSize: 1)
private let relay = PublishSubject<T>()
private let lock = NSRecursiveLock()
private let disposeBag = DisposeBag()
}
extension ObservableConvertibleType where Element == Error {
/// Monitors self for `.unauthorized` error events and passes all other errors on. When an `.unauthorized` error is seen, the `service` will get a new token and emit a signal that it's safe to retry the request.
///
/// - Parameter service: A `TokenAcquisitionService` object that is being used to store the auth token for the request.
/// - Returns: A trigger that will emit when it's safe to retry the request.
public func renewToken<T>(with service: TokenAcquisitionService<T>) -> Observable<Void> {
return service.trackErrors(for: self)
}
}
Once you put the above in your app, you can just add a .retryWhen { $0.renewToken(with: tokenAcquisitionService) } to the end of your request. Make sure your request emits a ResponseError.unauthorized if the token is unauthorized and the service will handle the retry.

I found a solution to my problem using DispatchWorkItem and controlling the entrance on my function with a boolean: isTokenRefreshing. Maybe that's not the most elegant solution, but it works.
So, in my NetworkManager class I added this two new properties:
public var savedRequests: [DispatchWorkItem] = []
public var isTokenRefreshing = false
Now in my SingleTrait extension, whenever I enter in the token refresh method I set the boolean isTokenRefreshing to true. So, if it's true, instead of starting another request, I simply throw a RefreshTokenProcessInProgressException and save the current request in my savedRequests array.
private func saveRequest(_ block: #escaping () -> Void) {
// Save request to DispatchWorkItem array
NetworkManager.shared.savedRequests.append( DispatchWorkItem {
block()
})
}
(Of course, that, if the token refresh succeeds you have to remember to continue all the savedRequests that are saved inside the array, it's not described inside the code down below yet).
Well, my SingleTrait extension is now something like this:
import Foundation
import Moya
import RxSwift
import Domain
public extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
private var refreshTokenParameters: TokenParameters {
TokenParameters(clientId: "pdappclient",
grantType: "refresh_token",
refreshToken: KeychainManager.shared.refreshToken)
}
func retryWithToken(target: MultiTarget) -> Single<E> {
return self.catchError { error -> Single<Response> in
if case Moya.MoyaError.statusCode(let response) = error {
if self.isTokenExpiredError(error) {
return Single.error(error)
} else {
return self.parseError(response: response)
}
}
return Single.error(error)
}
.retryToken(target: target)
.catchError { error -> Single<Response> in
if case Moya.MoyaError.statusCode(let response) = error {
return self.parseError(response: response)
}
return Single.error(error)
}
}
private func retryToken(target: MultiTarget) -> Single<E> {
let maxRetries = 1
return self.retryWhen({ error in
error
.enumerated()
.flatMap { (attempt, error) -> Observable<Int> in
if attempt >= maxRetries {
return Observable.error(error)
}
if self.isTokenExpiredError(error) {
return Observable<Int>.just(attempt + 1)
}
return Observable.error(error)
}
.flatMapFirst { _ -> Single<TokenResponse> in
if NetworkManager.shared.isTokenRefreshing {
self.saveRequest {
self.retryToken(target: target)
}
return Single.error(RefreshTokenProcessInProgressException())
} else {
return self.refreshTokenRequest()
}
}
.share()
.asObservable()
})
}
private func refreshTokenRequest() -> Single<TokenResponse> {
NetworkManager.shared.isTokenRefreshing = true
return NetworkManager.shared.fetchData(fromApi: IdentityServerAPI
.token(parameters: self.refreshTokenParameters))
.do(onSuccess: { tokenResponse in
KeychainManager.shared.accessToken = tokenResponse.accessToken
KeychainManager.shared.refreshToken = tokenResponse.refreshToken
}).catchError { error -> Single<TokenResponse> in
return Single.error(InvalidGrantException())
}
}
private func saveRequest(_ block: #escaping () -> Void) {
// Save request to DispatchWorkItem array
NetworkManager.shared.savedRequests.append( DispatchWorkItem {
block()
})
}
func parseError<E>(response: Response) -> Single<E> {
if response.statusCode == 401 {
// TODO
}
let decoder = JSONDecoder()
if let errors = try? response.map([BaseResponseError].self, atKeyPath: "errors", using: decoder,
failsOnEmptyData: true) {
return Single.error(BaseAPIErrorResponse(errors: errors))
}
return Single.error(APIError2.unknown)
}
func isTokenExpiredError(_ error: Error) -> Bool {
if let moyaError = error as? MoyaError {
switch moyaError {
case .statusCode(let response):
if response.statusCode != 401 {
return false
} else if response.data.count == 0 {
return true
}
default:
break
}
}
return false
}
func filterUnauthorized() -> Single<E> {
flatMap { (response) -> Single<E> in
if 200...299 ~= response.statusCode {
return Single.just(response)
} else if response.statusCode == 404 {
return Single.just(response)
} else {
return Single.error(MoyaError.statusCode(response))
}
}
}
func asRetriableAuthenticated(target: MultiTarget) -> Single<Element> {
filterUnauthorized()
.retryWithToken(target: target)
.filterStatusCode()
}
func filterStatusCode() -> Single<E> {
flatMap { (response) -> Single<E> in
if 200...299 ~= response.statusCode {
return Single.just(response)
} else {
return self.parseError(response: response)
}
}
}
}
In my case, if the token refresh fails, after a N number of retries, I restart the app. And so, whenever a restart the application I'm setting the isTokenRefreshing to false again.
This is the way I found to solve this problem. If you have another approach, please let me know.

Related

Observable extension with generic type

Context
I want to wrap the Alamofire.upload into an observable and having info regarding the upload progress.
For that I have created a custom UploadElement that is an enum representing either the progress and the value or the result. So far I have:
enum UploadElement<Result> where Result: Codable {
case progress(Double)
case response(Result)
}
private func buildUploadRequest(url: URL, parts: [Data]) -> Observable<UploadRequest> {
let uploadRequest = manager.upload(
multipartFormData: { multipartFormData in /* build multipart */ },
to: url
)
return Observable.just(uploadRequest)
}
func upload<Result: Codable>(url: URL, parts: [Data]) -> Observable<UploadElement<Result>> {
buildUploadRequest(url: url, parts: parts)
.flatMap { request in
Observable<UploadElement<Result>>.create { observer in
request.response { response in
do {
observer.on(.next(.response(/* decode here */)))
observer.on(.completed)
} catch let error {
observer.on(.error(error))
}
}.uploadProgress { progress in
observer.on(.next(.progress(progress.fractionCompleted)))
}
.resume()
return Disposable.create { request.cancel() }
}
}
}
Now I would like to have an extension on an Observable<UploadEment<Result>> to have a nicer way to be notified.
Basically it would be:
service.upload(url: ..., parts: ...)
.progress { progress in /* */ }
.result { result in /* */ }
.subscribe()
.dispose(by: disposeBag)
To do that I tried:
extension ObservableType where Element == UploadElement<Resource> {
func progress(progressCompletion: #escaping (Double) -> Void) -> Self {
return self.do(onNext: { element in
switch element {
case .progress(let progress): progressCompletion(progress)
case .response: return
}
})
}
func result(resultCompletion: #escaping (Result) -> Void) -> Self {
return self.do(onNext: { element in
switch element {
case .response(let result): resultCompletion(result)
case .progress: return
}
})
}
}
I tried multiple variation of that but the errors that I get are:
Cannot find 'Result in scope'
Reference to generic type ... required argument
Is it possible to achieve something like that?
You just need to move the where clause from class scope down to function scope (shown below).
That said, I don't think breaking out of the monad like this in the middle of a stream is "a nicer way to be notified".
Better would be to break your Observable into two streams and subscribe to each of them:
extension ObservableType {
func progress<Resource>() -> Observable<Double> where Element == UploadElement<Resource> {
self.compactMap { element in
switch element {
case let .progress(progress):
return progress
case .response:
return nil
}
}
}
func result<Resource>() -> Observable<Resource> where Element == UploadElement<Resource> {
self.compactMap { element in
switch element {
case .progress:
return nil
case let .response(resource):
return resource
}
}
}
}
With the above you can now do something like this:
let response = service.upload(url: ..., parts: ...)
.share()
response
.progress()
.subscribe(onNext: { progress in /*...*/ })
.disposed(by: disposeBag)
response
.result()
.subscribe(onNext: { result in /*...*/ })
.dispose(by: disposeBag)
Now you don't have any empty subscribes.
I found something that is working:
extension ObservableType {
func progress<O: Codable>(progressCompletion: #escaping (Double) -> Void) -> Observable<UploadElement<O>> where Element == UploadElement<O> {
return self.do(onNext: { element in
if case .progress(let progress) = element {
progressCompletion(progress)
}
})
}
func response<O: Codable>(responseCompletion: #escaping (O) -> Void) -> Observable<UploadElement<O>> where Element == UploadElement<O> {
return self.do(onNext: { element in
if case .response(let response) = element {
responseCompletion(response)
}
})
}
}
Now I can use the "planned" api:
service.update(data: /* ... */)
.progress { progress in /* */ }
.response { result in /* */ }
.subscribe(
onError: { error in /* */ }
)
.dispose(by: disposeBag)
However as Daniel mentioned this might not be the "nicer way of being notified".

How to call recursive function with Promise Kit?

I am stuck with somewhere to call same function again in promise and because of calling multiple time it's deallocate promise. Actually in my case I have API with multiple page request and I want to call it with promise. I was implemented it as below.
func fetchContacts() -> Promise<FPGetContactResponse?> {
return Promise { seal in
let contactrequest = FPGetContactRequest()
contactrequest.pageNo = getAPICurrentPageNo(Api.API_CONTACTS) + 1
contactrequest.pageSize = SMALL_PAGE_SIZE
contactrequest.doGetContacts(parameter: [:], response: { (response) in
print("Contacts Count : \(response.Contacts?.count ?? 0)")
if(response.Contacts?.count ?? 0 != 0){
_ = self.fetchContacts()
}else{
seal.fulfill(response)
}
})
{ (error) in
print(error.localizedDescription)
seal.reject(error)
}
}
}
In above function I check for contact count != 0 then I need to call same function again. But unfortunately it's deallocate promise.
I call promise sequence like below.
func startSyncData(handler:#escaping SyncAPIHandler){
firstly {
self.fetchContacts().ensure {
handler(false,0.5,nil)
}
}.then { data in
self.fetchInteractions().ensure {
handler(false,0.7,nil)
}
}.then { data in
self.fetchAddresses().ensure {
handler(false,0.8,nil)
}
}.then { data in
self.fetchLookupQuery().ensure {
}
}
.done { contacts -> Void in
//Do something with the JSON info
print("Contacts Done")
handler(true,0.8,nil)
}
.catch(policy: .allErrors) { error in
print(error.localizedDescription)
}
}
Please provide me the right way to call same function again in promise.
Instead of using recursion you should return a response within your promise and check it inside next .then and call fetchContacts again if it's needed:
fetchContacts()
.then { response -> Promise<FPGetContactResponse> in
if (response.Contacts?.count ?? 0 != 0) {
return fetchContacts() // Make the second call
}
return .value(response) // Return fullfilled promise
}
.then {
...
}
Also you can make a special wrapper for your case using the next approach - https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#retry--polling
I implemented things with following solution.
func syncContacts() -> Promise<FPGetContactResponse?> {
return fetchContacts().then{ seal -> Promise<FPGetContactResponse?> in
if(seal?.Contacts?.count ?? 0 != 0){
return self.syncContacts()
}else{
return Promise.value(seal)
}
}
}
Now just call syncContacts() method in promise sequence, like below.
func startSyncData(handler:#escaping SyncAPIHandler){
firstly {
self.syncContacts().ensure {
handler(false,0.5,nil)
}
}.then { data in
self.syncInterections().ensure {
handler(false,0.7,nil)
}
}.then { data in
self.syncAddresses().ensure {
handler(false,0.8,nil)
}
}.then { data in
self.syncLookupQuery().ensure {
}
}
.done { contacts -> Void in
//Do something with the JSON info
print("Contacts Done")
handler(true,0.8,nil)
}
.catch(policy: .allErrors) { error in
print(error.localizedDescription)
}
}

How to always return an array in Vapor 3 and Fluent (even for single entity requests)

I'd like to have an index controller function that returns an array of entities if no request parameter is set or a single entity if the id parameter is set. However, I'd like to always receive an array, in the latter case it just contains only one element.
Here's my function:
final class AddressController {
func index(_ req: Request) throws -> Future<[Address]> {
if let id = try? req.query.get(UUID.self, at: "id") {
// THIS IS NOT WORKING...
return Address.find(id, on: req)
} else {
return Address.query(on: req).all()
}
}
}
final class AddressController {
func index(_ req: Request) throws -> Future<[Address]> {
if let id = try? req.query.get(UUID.self, at: "id") {
return Address.find(id, on: req).map {
guard let address = $0 else { return [] }
return [address]
}
} else {
return Address.query(on: req).all()
}
}
}

Handling 401 status w/ RxSwift & URLSession

I currently have a network client that looks like the below:
class Client<R: ResourceType> {
let engine: ClientEngineType
var session: URLSession
init(engine: ClientEngineType = ClientEngine()) {
self.engine = engine
self.session = URLSession.shared
}
func request<T: Codable>(_ resource: R) -> Single<T> {
let request = URLRequest(resource: resource)
return Single<T>.create { [weak self] single in
guard let self = self else { return Disposables.create() }
let response = self.session.rx.response(request: request)
return response.subscribe(
onNext: { response, data in
if let error = self.error(from: response) {
single(.error(error))
return
}
do {
let decoder = JSONDecoder()
let value = try decoder.decode(T.self, from: data)
single(.success(value))
} catch let error {
single(.error(error))
}
},
onError: { error in
single(.error(error))
})
}
}
struct StatusCodeError: LocalizedError {
let code: Int
var errorDescription: String? {
return "An error occurred communicating with the server. Please try again."
}
}
private func error(from response: URLResponse?) -> Error? {
guard let response = response as? HTTPURLResponse else { return nil }
let statusCode = response.statusCode
if 200..<300 ~= statusCode {
return nil
} else {
return StatusCodeError(code: statusCode)
}
}
}
Which I can then invoke something like
let client = Client<MyRoutes>()
client.request(.companyProps(params: ["collections": "settings"]))
.map { props -> CompanyModel in return props }
.subscribe(onSuccess: { props in
// do something with props
}) { error in
print(error.localizedDescription)
}.disposed(by: disposeBag)
I'd like to start handling 401 responses and refreshing my token and retrying the request.
I'm struggling to find a nice way to do this.
I found this excellent gist that outlines a way to achieve this, however I am struggling to implement this in my current client.
Any tips or pointers would be very much appreciated.
That's my gist! (Thanks for calling it excellent.) Did you see the article that went with it? https://medium.com/#danielt1263/retrying-a-network-request-despite-having-an-invalid-token-b8b89340d29
There are two key elements in handling 401 retries. First is that you need a way to insert tokens into your requests and start your request pipeline with Observable.deferred { tokenAcquisitionService.token.take(1) }. In your case, that means you need a URLRequest.init that will accept a Resource and a token, not just a resource.
The second is to throw a TokenAcquisitionError.unauthorized error when you get a 401 and end your request pipeline with .retryWhen { $0.renewToken(with: tokenAcquisitionService) }
So, given what you have above, in order to handle token retries all you need to do is bring my TokenAcquisitionService into your project and use this:
func getToken(_ oldToken: Token) -> Observable<(response: HTTPURLResponse, data: Data)> {
fatalError("this function needs to be able to request a new token from the server. It has access to the old token if it needs that to request the new one.")
}
func extractToken(_ data: Data) -> Token {
fatalError("This function needs to be able to extract the new token using the data returned from the previous function.")
}
let tokenAcquisitionService = TokenAcquisitionService<Token>(initialToken: Token(), getToken: getToken, extractToken: extractToken)
final class Client<R> where R: ResourceType {
let session: URLSession
init(session: URLSession = URLSession.shared) {
self.session = session
}
func request<T>(_ resource: R) -> Single<T> where T: Decodable {
return Observable.deferred { tokenAcquisitionService.token.take(1) }
.map { token in URLRequest(resource: resource, token: token) }
.flatMapLatest { [session] request in session.rx.response(request: request) }
.do(onNext: { response, _ in
if response.statusCode == 401 {
throw TokenAcquisitionError.unauthorized
}
})
.map { (_, data) -> T in
return try JSONDecoder().decode(T.self, from: data)
}
.retryWhen { $0.renewToken(with: tokenAcquisitionService) }
.asSingle()
}
}
Note, it could be the case that the getToken function has to, for example, present a view controller that asks for the user's credentials. That means you need to present your login view controller (or a UIAlertController) to gather the data. Or maybe you get both an authorization token and a refresh token from your server when you login. In that case the TokenAcquisitionService should hold on to both of them (i.e., its T should be a (token: String, refresh: String). Either is fine.
The only problem with the service is that if acquiring the new token fails, the entire service shuts down. I haven't fixed that yet.

RxSwift renew Authentication Token

Hy I'm trying to come up with a solution using Moya and RxSwift that renews an Authentication token and retries the requests.
The problem is I have multiple requests going on at the same time, so lets say 10 requests fire while the Authentication token has expired, I will try to renew the token on all of them, and as soon as the first one renews the other ones will fail because they use a wrong token to renew.
What I would like to do is just build a queue (maybe) of requests and then retry those. Not sure if this is the best scenario for this.
This is what I have so far:
final class NetworkOnlineProvider {
fileprivate let database = DatabaseClient(database: DatabaseRealm()).database
fileprivate let provider: MoyaProvider<NetworkAPI>
init(endpointClosure: #escaping MoyaProvider<NetworkAPI>.EndpointClosure = MoyaProvider<NetworkAPI>.defaultEndpointMapping,
requestClosure: #escaping MoyaProvider<NetworkAPI>.RequestClosure = MoyaProvider<NetworkAPI>.defaultRequestMapping,
stubClosure: #escaping MoyaProvider<NetworkAPI>.StubClosure = MoyaProvider.neverStub,
manager: Manager = MoyaProvider<NetworkAPI>.defaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights: Bool = false) {
self.provider = MoyaProvider(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights)
}
fileprivate func getJWTRenewRequest() -> Single<Response>? {
if let token = JWTManager.sharedInstance.token {
return provider.rx.request(.renew(token: token))
}
return nil
}
func tokenRequest() -> Single<String> {
let errorSingle = Single<String>.create { single in
single(.error(APIError.failure))
return Disposables.create()
}
let emptyJWTSingle = Single<String>.create { single in
single(.success(""))
return Disposables.create()
}
// Return if no token found
guard let appToken = JWTManager.sharedInstance.getJWT() else {
return refreshToken() ?? emptyJWTSingle
}
// If we have a valid token, just return it
if !appToken.hasTokenExpired {
return Single<String>.create { single in
single(.success(appToken.token))
return Disposables.create()
}
}
// Token has expired
let newTokenRequest = refreshToken()
return newTokenRequest ?? errorSingle
}
func refreshToken() -> Single<String>? {
return getJWTRenewRequest()?
.debug("Renewing JWT")
.filterSuccessfulStatusCodes()
.map { (response: Response) -> (token: String, expiration: Double) in
guard let json = try? JSON(data: response.data) else { throw RxError.unknown }
let success = json["success"]
guard
let jwt = success["jwt"].string,
let jwt_expiration = success["jwt_expiration"].double,
let valid_login = success["valid_login"].bool, valid_login
else { throw RxError.unknown }
return (token: jwt, expiration: jwt_expiration)
}
.do(onSuccess: { (token: String, expiration: Double) in
JWTManager.sharedInstance.save(token: JWT(token: token, expiration: String(expiration)))
})
.map { (token: String, expiration: Double) in
return token
}
.catchError { e -> Single<String> in
print("Failed to Renew JWT")
JWTManager.sharedInstance.delete()
UIApplication.shared.appDelegate.cleanPreviousContext(jwt: true)
let loginVC = UIStoryboard(storyboard: .login).instantiateViewController(vc: LoginViewController.self)
UIApplication.shared.appDelegate.window?.setRootViewController(UINavigationController(rootViewController: loginVC))
throw e
}
}
func request(_ target: NetworkAPI) -> Single<Response> {
let actualRequest = provider.rx.request(target)
if target.isAuthenticatedCall {
return tokenRequest().flatMap { _ in
actualRequest
}
}
return actualRequest
}
}
The solution is here: RxSwift and Retrying a Network Request Despite Having an Invalid Token
The key is to use flatMapFirst so you only make one request for the first 401 and ignore other 401s while that request is in flight.
The gist associated with the article includes unit tests proving it works.