Refresh token issue AuthenticationInterceptor for Alamofire 5 - ios

I implemented the new AuthenticationInterceptor into my app, here is my actual code:
import Alamofire
import SwiftyJSON
struct OAuthCredential: AuthenticationCredential {
let accessToken: String
let refreshToken: String
let expiration: Date
// Require refresh if within 5 minutes of expiration
var requiresRefresh: Bool { Date(timeIntervalSinceNow: 60 * 15) > expiration }
}
class OAuthAuthenticator: Authenticator {
func apply(_ credential: OAuthCredential, to urlRequest: inout URLRequest) {
urlRequest.headers.add(.authorization(bearerToken: credential.accessToken))
}
func refresh(_ credential: OAuthCredential, for session: Session, completion: #escaping (Result<OAuthCredential, Error>) -> Void) {
NetworkManager.shared.oauth.doRefreshToken { (jsonDict, error) in
if let jsonDict = jsonDict {
let json = JSON(jsonDict)
let accessToken = json["access_token"].stringValue
let refreshToken = json["refresh_token"].stringValue
let expiration = json["expires_in"].doubleValue
let newCredential = OAuthCredential(accessToken: accessToken, refreshToken: refreshToken, expiration: Date(timeIntervalSinceNow: expiration))
completion(.success(newCredential))
}
}
}
func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool {
return response.statusCode == 401
}
func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: OAuthCredential) -> Bool {
let bearerToken = HTTPHeader.authorization(bearerToken: credential.accessToken).value
return urlRequest.headers["Authorization"] == bearerToken
}
}
The problem here is when for example I enter a screen where there're 3 API calls, refresh delegate is called also 3 times and refresh the token 3 times also.
What I want to achieve is to call "doRefreshToken" once and recall all APIs with the new token.
Thanks in advance.

You need to implement the RequestAdapter, RequestRetrier also with its methods.
Here is a good answer by #m1sh0
Alamofire auto refresh token and retry previous API call in iOS Swift 4

Related

AuthenticationInterceptor(Alamofire5.2) retry process doesn't work well

I have a question about the AuthenticationInterceptor added in Alamofire 5.2.
I am using AuthenticationInterceptor to refresh the oAuth token.
https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#authenticationinterceptor
The code I'm trying is below.
struct OAuthCredential: AuthenticationCredential {
let accessToken: String
let refreshToken: String
let userID: String
let expiration: Date
// Require refresh if within 5 minutes of expiration
var requiresRefresh: Bool { Date(timeIntervalSinceNow: 60 * 5) > expiration }
}
class OAuthAuthenticator: Authenticator {
func apply(_ credential: OAuthCredential, to urlRequest: inout URLRequest) {
urlRequest.headers.add(.authorization(bearerToken: credential.accessToken))
}
func refresh(_ credential: OAuthCredential,
for session: Session,
completion: #escaping (Result<OAuthCredential, Error>) -> Void) {
// Request to refresh token
let request = Session.default.request(
URL(string: "URL for token refresh")!,
method: .patch,
parameters: ["refresh_token": credential.refreshToken]
)
request.responseJSON { response in
// Get new Credential information
// ~~~~~~
completion(.success(newCredential))
}
}
func didRequest(_ urlRequest: URLRequest,
with response: HTTPURLResponse,
failDueToAuthenticationError error: Error) -> Bool {
return response.statusCode == 401
}
func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: OAuthCredential) -> Bool {
let bearerToken = HTTPHeader.authorization(bearerToken: credential.accessToken).value
return urlRequest.headers["Authorization"] == bearerToken
}
}
// ~~~~~~
let session = Session.default
let urlRequest = try! URLRequest(
url: URL(string: "https://api.example/docs")!,
method: .get
)
session.request(urlRequest, interceptor: interceptor).responseJSON { response in
// ~~~~~
}
What I don't know is whether didRequest and isRequest are sometimes called. I debugged while pasting a breakpoint when I got a 401 error, but it didn't stop at the above method.
The reason those methods weren't called was that they would always be returned on the line below.
https://github.com/Alamofire/Alamofire/blob/4f72b95b49c22e445e1866712f719698fa11c30c/Source/AuthenticationInterceptor.swift#L297
I couldn't find a case that didn't go through this line.
I would like to know the case where two methods are called.
try to call a .validate()
session.request(urlRequest, interceptor: interceptor).validate().responseJSON { response in
// ~~~~~
}

Chaining API calls

I've built myself an APIService class, handling all interaction with APIs my App is using
func callEndpointX(token: String, completion: #escaping(Result<User, APIError>) -> Void) {
guard let endpoint = URL(string: apiBaseUrl + "/endpointX") else {fatalError()}
var request = URLRequest(url: endpoint)
request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let jsonData = data
else { ... completion(.failure(.responseError)); return }
do {
let response = try JSONDecoder()...
completion(.success(response.detailresponse!))
} catch {
...
completion(.failure(.decodingError))
}
}
dataTask.resume()
}
My challenge is that the Bearer Tokens I'm passing along do expire. What I would like to do in case of an expired token is to silently refresh the token for the user before hitting the api.
So I've got a mini function func tokenExpired() -> Bool {...} checking if the Token has alreaady expired and I have access to another API all refreshToken in a similar way as func callEndpointX above.
What I'm struggling with is how to chain these together to avoid race conditions - i.e. when func callEndpointX gets called, it should check func tokenExpired() and not continue any other work until that's done. If expired, it should first execute refreshToken and only after that returns continue with finally executing the ret of func callEndpointX.
All this chaining is messing with my brain and I was hoping someone would be able to guide me here.
Many thanks!!!
A solution is to call recursively callEndPointX after token refresh is completed.
Assume your token request is like this:
func requestToken(completion:#escaping((String) -> Void))
then
func callEndpointX(token: String, completion: #escaping(Result<User, APIError>) -> Void) {
if tokenExpired() {
requestToken(completion: { newToken in
callEndpointX(token: newToken, completion: completion)
})
}
else {
// your code for callendpointX
}
}

Right way to refresh the token

There is a function getUser in RequestManager class that called in my VC.
func getUser(onCompletion: #escaping (_ result: User?, error: String?) -> Void) {
Alamofire.request(Router.getUser).responseJSON { (response) in
// here is the work with response
}
}
If this request returns 403 it means access_token is expired. I need to refresh token and repeat the request from my VC.
Now the question.
How to refresh token and repeat the request in the right way?
To handle the error and refresh token in MyViewController or getUser method is not good idea because I have a lot of VCs and request methods.
I need something like: VC calls the method and gets the User even if token is expired and refreshToken must not be in all request methods.
EDIT
refreshToken method
func refreshToken(onCompletion: #escaping (_ result: Bool?) -> Void) {
Alamofire.request(Router.refreshToken).responseJSON { (response) in
print(response)
if response.response?.statusCode == 200 {
guard let data = response.data else { return onCompletion(false) }
let token = try? JSONDecoder().decode(Token.self, from: data)
token?.setToken()
onCompletion(true)
} else {
onCompletion(false)
}
}
}
To solve this, I created a class from which we will call every API, say BaseService.swift.
BaseService.swift :
import Foundation
import Alamofire
import iComponents
struct AlamofireRequestModal {
var method: Alamofire.HTTPMethod
var path: String
var parameters: [String: AnyObject]?
var encoding: ParameterEncoding
var headers: [String: String]?
init() {
method = .get
path = ""
parameters = nil
encoding = JSONEncoding() as ParameterEncoding
headers = ["Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
"Cache-Control": "no-cache"]
}
}
class BaseService: NSObject {
func callWebServiceAlamofire(_ alamoReq: AlamofireRequestModal, success: #escaping ((_ responseObject: AnyObject?) -> Void), failure: #escaping ((_ error: NSError?) -> Void)) {
// Create alamofire request
// "alamoReq" is overridden in services, which will create a request here
let req = Alamofire.request(alamoReq.path, method: alamoReq.method, parameters: alamoReq.parameters, encoding: alamoReq.encoding, headers: alamoReq.headers)
// Call response handler method of alamofire
req.validate(statusCode: 200..<600).responseJSON(completionHandler: { response in
let statusCode = response.response?.statusCode
switch response.result {
case .success(let data):
if statusCode == 200 {
Logs.DLog(object: "\n Success: \(response)")
success(data as AnyObject?)
} else if statusCode == 403 {
// Access token expire
self.requestForGetNewAccessToken(alaomReq: alamoReq, success: success, failure: failure)
} else {
let errorDict: [String: Any] = ((data as? NSDictionary)! as? [String: Any])!
Logs.DLog(object: "\n \(errorDict)")
failure(errorTemp as NSError?)
}
case .failure(let error):
Logs.DLog(object: "\n Failure: \(error.localizedDescription)")
failure(error as NSError?)
}
})
}
}
extension BaseService {
func getAccessToken() -> String {
if let accessToken = UserDefaults.standard.value(forKey: UserDefault.userAccessToken) as? String {
return "Bearer " + accessToken
} else {
return ""
}
}
// MARK: - API CALL
func requestForGetNewAccessToken(alaomReq: AlamofireRequestModal, success: #escaping ((_ responseObject: AnyObject?) -> Void), failure: #escaping ((_ error: NSError?) -> Void) ) {
UserModal().getAccessToken(success: { (responseObj) in
if let accessToken = responseObj?.value(forKey: "accessToken") {
UserDefaults.standard.set(accessToken, forKey: UserDefault.userAccessToken)
}
// override existing alaomReq (updating token in header)
var request: AlamofireRequestModal = alaomReq
request.headers = ["Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
"Cache-Control": "no-cache",
"X-Authorization": self.getAccessToken()]
self.callWebServiceAlamofire(request, success: success, failure: failure)
}, failure: { (_) in
self.requestForGetNewAccessToken(alaomReq: alaomReq, success: success, failure: failure)
})
}
}
For calling the API from this call, we need to create a object of AlamofireRequestModal and override it with necessary parameter.
For example I created a file APIService.swift in which we have a method for getUserProfileData.
APIService.swift :
import Foundation
let GET_USER_PROFILE_METHOD = "user/profile"
struct BaseURL {
// Local Server
static let urlString: String = "http://192.168.10.236: 8084/"
// QAT Server
// static let urlString: String = "http://192.171.286.74: 8080/"
static let staging: String = BaseURL.urlString + "api/v1/"
}
class APIService: BaseService {
func getUserProfile(success: #escaping ((_ responseObject: AnyObject?) -> Void), failure: #escaping ((_ error: NSError?) -> Void)) {
var request: AlamofireRequestModal = AlamofireRequestModal()
request.method = .get
request.path = BaseURL.staging + GET_USER_PROFILE_METHOD
request.headers = ["Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
"Cache-Control": "no-cache",
"X-Authorization": getAccessToken()]
self.callWebServiceAlamofire(request, success: success, failure: failure)
}
}
Explanation:
In code block:
else if statusCode == 403 {
// Access token expire
self.requestForGetNewAccessToken(alaomReq: alamoReq, success: success, failure: failure)
}
I call getNewAccessToken API (say refresh-token, in your case), with the request( it could be any request based from APIService.swift).
When we get new token I save it user-defaults then I will update the request( the one I am getting as a parameter in refresh-token API call), and will pass the success and failure block as it is.
You can create generic refresher class:
protocol IRefresher {
associatedtype RefreshTarget: IRefreshing
var target: RefreshTarget? { get }
func launch(repeats: Bool, timeInterval: TimeInterval)
func invalidate()
}
class Refresher<T: IRefreshing>: IRefresher {
internal weak var target: T?
private var timer: Timer?
init(target: T?) {
self.target = target
}
public func launch(repeats: Bool, timeInterval: TimeInterval) {
timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: repeats) { [weak self] (timer) in
self?.target?.refresh()
}
}
public func invalidate() {
timer?.invalidate()
}
}
And the refresh target protocol:
protocol IRefreshing: class {
func refresh()
}
Define new typealias:
typealias RequestManagerRefresher = Refresher<RequestManager>
Now create refresher and store it:
class RequestManager {
let refresher: RequestManagerRefresher
init() {
refresher = Refresher(target: self)
refresher?.launch(repeats: true, timeInterval: 15*60)
}
}
And expand RequestManager:
extension RequestManager: IRefreshing {
func refresh() {
updateToken()
}
}
Every 15 minutes your RequestManager's token will be updated
UPDATE
Of course, you also can change the update time. Create a static var that storing update time you need. For example inside the RequestManager:
class RequestManager {
static var updateInterval: TimeInterval = 0
let refresher: RequestManagerRefresher
init() {
refresher = Refresher(target: self)
refresher?.launch(repeats: true, timeInterval: updateInterval)
}
}
So now you can ask the token provider server for token update interval and set this value to updateInterval static var:
backendTokenUpdateIntervalRequest() { interval in
RequestManager.updateInterval = interval
}
You can easily Refresh token and retry your previous API call using Alamofire
RequestInterceptor
NetworkManager.Swift:-
import Alamofire
class NetworkManager {
static let shared: NetworkManager = {
return NetworkManager()
}()
typealias completionHandler = ((Result<Data, CustomError>) -> Void)
var request: Alamofire.Request?
let retryLimit = 3
func request(_ url: String, method: HTTPMethod = .get, parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.queryString, headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil, completion: #escaping completionHandler) {
AF.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers, interceptor: interceptor ?? self).validate().responseJSON { (response) in
if let data = response.data {
completion(.success(data))
} else {
completion(.failure())
}
}
}
}
RequestInterceptor.swift :-
import Alamofire
extension NetworkManager: RequestInterceptor {
func adapt(_ urlRequest: URLRequest, for session: Session, completion: #escaping (Result<URLRequest, Error>) -> Void) {
var request = urlRequest
guard let token = UserDefaultsManager.shared.getToken() else {
completion(.success(urlRequest))
return
}
let bearerToken = "Bearer \(token)"
request.setValue(bearerToken, forHTTPHeaderField: "Authorization")
print("\nadapted; token added to the header field is: \(bearerToken)\n")
completion(.success(request))
}
func retry(_ request: Request, for session: Session, dueTo error: Error,
completion: #escaping (RetryResult) -> Void) {
guard let statusCode = request.response?.statusCode else {
completion(.doNotRetry)
return
}
guard request.retryCount < retryLimit else {
completion(.doNotRetry)
return
}
print("retry statusCode....\(statusCode)")
switch statusCode {
case 200...299:
completion(.doNotRetry)
case 401:
refreshToken { isSuccess in isSuccess ? completion(.retry) : completion(.doNotRetry) }
break
default:
completion(.retry)
}
}
func refreshToken(completion: #escaping (_ isSuccess: Bool) -> Void) {
let params = [
"refresh_token": Helpers.getStringValueForKey(Constants.REFRESH_TOKEN)
]
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { response in
if let data = response.data, let token = (try? JSONSerialization.jsonObject(with: data, options: [])
as? [String: Any])?["access_token"] as? String {
UserDefaultsManager.shared.setToken(token: token)
print("\nRefresh token completed successfully. New token is: \(token)\n")
completion(true)
} else {
completion(false)
}
}
}
}
Alamofire v5 has a property named RequestInterceptor.
RequestInterceptor has two method, one is Adapt which assign
access_token to any Network call header, second one is Retry method.
In Retry method we can check response status code and call
refresh_token block to get new token and retry previous API again.

Alamofire 4 retrier and adaptor unable to see the changed accessToken

I am fetching new access token with alamofire's retrier and adapt protocol. I am able to fetch a new token but sometimes when another thread is calling the same method, it is not working and the request fails even when new access Token is generated.
I have just changed the example and now I am using synchronous request to fetch access Token as I don't want to send an extra request in adapt if I get to know token is invalid.
The strange issue is that when I print the response on the failed request, I see that request still had the old token in the header. What am I missing here?
func isTokenValid() -> Bool {
return Date() < self.expiryTime
}
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var urlRequest = urlRequest
urlRequest = processRequest(urlRequest: urlRequest)
return urlRequest
}
func processRequest(urlRequest: URLRequest) -> URLRequest {
DDLogInfo("******access token : \(self.accessToken)***************")
DDLogInfo("***** expiry Time: \(self.expiryTime)***************")
var urlRequest = urlRequest
lock.lock(); defer { DDLogInfo( "Thread UnLocked ⚡️: \(Thread.current)\r" + "🏭: \(OperationQueue.current?.underlyingQueue?.label ?? "None")\r")
lock.unlock()
}
DDLogInfo( "Thread Locked ⚡️: \(Thread.current)\r" + "🏭: \(OperationQueue.current?.underlyingQueue?.label ?? "None")\r")
if !isTokenValid() {
let _ = self.refreshAccessToken()
}
urlRequest = self.appendToken(urlRequest: urlRequest)
DDLogInfo("here \(urlRequest)")
return urlRequest
}
func appendToken(urlRequest: URLRequest) -> URLRequest {
if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) {
var urlRequest = urlRequest
DDLogInfo("token appended : \(self.accessToken)")
urlRequest.setValue(self.accessToken, forHTTPHeaderField: Constants.KeychainKeys.accessToken)
}
return urlRequest
}
// MARK: - RequestRetrier
func handleFailedRequest(_ completion: #escaping RequestRetryCompletion) {
requestsToRetry.append(completion)
if !isRefreshing {
lock.lock()
print( "Thread Locked⚡️: \(Thread.current)\r" + "🏭: \(OperationQueue.current?.underlyingQueue?.label ?? "None")\r")
let succeeded = self.refreshAccessToken()
self.requestsToRetry.forEach {
print("token fetched \(succeeded): \(self.accessToken)")
$0(succeeded, 0.0)
}
self.requestsToRetry.removeAll()
DDLogInfo( "Thread UnLocked⚡️: \(Thread.current)\r" + "🏭: \(OperationQueue.current?.underlyingQueue?.label ?? "None")\r")
lock.unlock()
}
}
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: #escaping RequestRetryCompletion) {
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401, request.retryCount < 3 {
handleFailedRequest(completion)
} else {
completion(false, 0.0)
}
}
func updateTokens (accessToken: String, refreshToken: String, accessTokenExpiresIn: Double) {
self.accessToken = accessToken
self.refreshToken = refreshToken
let expiryDate = Date(timeIntervalSinceNow: accessTokenExpiresIn - Constants.KeychainKeys.expirationBuffer)
AppSettings.sharedInstance.tokenExpiryTime = expiryDate
self.expiryTime = expiryDate
do {try keychainWrapper.save(values: ["accessToken": self.accessToken, "refreshToken": self.refreshToken])} catch {
DDLogError("unable to save accessToken")
}
}
// MARK: - Private - Refresh Tokens
fileprivate func refreshAccessToken() -> Bool {
DDLogInfo("^^^^^^^^")
Thread.callStackSymbols.forEach { DDLogInfo($0) }
var success = false
guard !isRefreshing else { return success }
let refreshRequest = URLRequestConfigurations.configRefreshProviderAgent(refreshToken: self.refreshToken)
let result = URLSession.shared.synchronousDataTask(with: refreshRequest)
self.isRefreshing = false
do {
if let data = result.0, let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] {
if let accessToken = json["accessToken"] as? String, let refreshToken = json["refreshToken"] as? String, let time = json["accessTokenExpiresIn"] as? Double {
updateTokens(accessToken: accessToken, refreshToken: refreshToken, accessTokenExpiresIn: time)
success = true
} else {
DDLogError("unable to find tokens/expiryInterval from refresh request")
}
} else {
DDLogError("unable to receive data from refresh request")
}
} catch {
DDLogError("unable to parse json response from refersh token request")
}
return success
}
Can you check by creating singleton class for network activity. The singleton pattern guarantees that only one instance of a class is instantiated. Like this way:-
open class NetworkHelper {
class var sharedManager: NetworkHelper {
struct Static{
static let instance: NetworkHelper = NetworkHelper()
}
return Static.instance
}
.... Put you network call method here
}
I have already faced the same issue with AFNetworking. unfortunately, Reasons behind are very silly. After 2-3 days R&D, I found it is happens due to coockies and caches.
Let's understand basic about Alamofire
Alamofire is basically a wrapper around NSURLSession. Its manager uses a default NSURLSessionConfiguration by calling `defaultSessionConfiguration()
NSURLSessionConfiguration reference for defaultSessionConfiguration() says:
The default session configuration uses a persistent disk-based cache
(except when the result is downloaded to a file) and stores
credentials in the user’s keychain. It also stores cookies (by
default) in the same shared cookie store as the NSURLConnection and
NSURLDownload classes.
Just disable caching for your API by using below code.
Disabling the URLCache
let manager: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.URLCache = nil
return Manager(configuration: configuration)
}()
Or you can also Configuring the Request Cache Policy
let manager: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData
return Manager(configuration: configuration)
}()
Solution: Just disable chaching for your APIs. It willl work for me. In your case may be it will for you.
I found the answer to the problem.
In adapt method I had to use a different variable for urlRequest as it was not modifying the request when using the same variable name. As you can see below I changed the variable to "mutableRequest"
func appendToken(urlRequest: URLRequest) -> URLRequest {
var mutableRequest = urlRequest
if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) {
DDLogInfo("token appended : \(self.accessToken)")
mutableRequest.setValue(self.accessToken, forHTTPHeaderField: Constants.KeychainKeys.accessToken)
}
return mutableRequest
}

Alamofire : How to handle errors globally

My question is quite similar to this one, but for Alamofire : AFNetworking: Handle error globally and repeat request
How to be able to catch globally an error (typically a 401) and handle it before other requests are made (and eventually failed if not managed) ?
I was thinking of chaining a custom response handler, but that's silly to do it on each request of the app.
Maybe subclassing, but which class should i subclass to handle that ?
Handling refresh for 401 responses in an oauth flow is quite complicated given the parallel nature of NSURLSessions. I have spent quite some time building an internal solution that has worked extremely well for us. The following is a very high level extraction of the general idea of how it was implemented.
import Foundation
import Alamofire
public class AuthorizationManager: Manager {
public typealias NetworkSuccessHandler = (AnyObject?) -> Void
public typealias NetworkFailureHandler = (NSHTTPURLResponse?, AnyObject?, NSError) -> Void
private typealias CachedTask = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void
private var cachedTasks = Array<CachedTask>()
private var isRefreshing = false
public func startRequest(
method method: Alamofire.Method,
URLString: URLStringConvertible,
parameters: [String: AnyObject]?,
encoding: ParameterEncoding,
success: NetworkSuccessHandler?,
failure: NetworkFailureHandler?) -> Request?
{
let cachedTask: CachedTask = { [weak self] URLResponse, data, error in
guard let strongSelf = self else { return }
if let error = error {
failure?(URLResponse, data, error)
} else {
strongSelf.startRequest(
method: method,
URLString: URLString,
parameters: parameters,
encoding: encoding,
success: success,
failure: failure
)
}
}
if self.isRefreshing {
self.cachedTasks.append(cachedTask)
return nil
}
// Append your auth tokens here to your parameters
let request = self.request(method, URLString, parameters: parameters, encoding: encoding)
request.response { [weak self] request, response, data, error in
guard let strongSelf = self else { return }
if let response = response where response.statusCode == 401 {
strongSelf.cachedTasks.append(cachedTask)
strongSelf.refreshTokens()
return
}
if let error = error {
failure?(response, data, error)
} else {
success?(data)
}
}
return request
}
func refreshTokens() {
self.isRefreshing = true
// Make the refresh call and run the following in the success closure to restart the cached tasks
let cachedTaskCopy = self.cachedTasks
self.cachedTasks.removeAll()
cachedTaskCopy.map { $0(nil, nil, nil) }
self.isRefreshing = false
}
}
The most important thing here to remember is that you don't want to run a refresh call for every 401 that comes back. A large number of requests can be racing at the same time. Therefore, you want to act on the first 401, and queue all the additional requests until the 401 has succeeded. The solution I outlined above does exactly that. Any data task that is started through the startRequest method will automatically get refreshed if it hits a 401.
Some other important things to note here that are not accounted for in this very simplified example are:
Thread-safety
Guaranteed success or failure closure calls
Storing and fetching the oauth tokens
Parsing the response
Casting the parsed response to the appropriate type (generics)
Hopefully this helps shed some light.
Update
We have now released 🔥🔥 Alamofire 4.0 🔥🔥 which adds the RequestAdapter and RequestRetrier protocols allowing you to easily build your own authentication system regardless of the authorization implementation details! For more information, please refer to our README which has a complete example of how you could implement on OAuth2 system into your app.
Full Disclosure: The example in the README is only meant to be used as an example. Please please please do NOT just go and copy-paste the code into a production application.
in Alamofire 5 you can use RequestInterceptor
Here is my error handling for 401 error in one of my projects, every requests that I pass the EnvironmentInterceptor to it the func of retry will be called if the request get to error
and also the adapt func can help you to add default value to your requests
struct EnvironmentInterceptor: RequestInterceptor {
func adapt(_ urlRequest: URLRequest, for session: Session, completion: #escaping (AFResult<URLRequest>) -> Void) {
var adaptedRequest = urlRequest
guard let token = KeychainWrapper.standard.string(forKey: KeychainsKeys.token.rawValue) else {
completion(.success(adaptedRequest))
return
}
adaptedRequest.setValue("Bearer \(token)", forHTTPHeaderField: HTTPHeaderField.authentication.rawValue)
completion(.success(adaptedRequest))
}
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: #escaping (RetryResult) -> Void) {
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
//get token
guard let refreshToken = KeychainWrapper.standard.string(forKey: KeychainsKeys.refreshToken.rawValue) else {
completion(.doNotRetryWithError(error))
return
}
APIDriverAcountClient.refreshToken(refreshToken: refreshToken) { res in
switch res {
case .success(let response):
let saveAccessToken: Bool = KeychainWrapper.standard.set(response.accessToken, forKey: KeychainsKeys.token.rawValue)
let saveRefreshToken: Bool = KeychainWrapper.standard.set(response.refreshToken, forKey: KeychainsKeys.refreshToken.rawValue)
let saveUserId: Bool = KeychainWrapper.standard.set(response.userId, forKey: KeychainsKeys.uId.rawValue)
print("is accesstoken saved ?: \(saveAccessToken)")
print("is refreshToken saved ?: \(saveRefreshToken)")
print("is userID saved ?: \(saveUserId)")
completion(.retry)
break
case .failure(let err):
//TODO logout
break
}
}
} else {
completion(.doNotRetry)
}
}
and you can use it like this :
#discardableResult
private static func performRequest<T: Decodable>(route: ApiDriverTrip, decoder: JSONDecoder = JSONDecoder(), completion: #escaping (AFResult<T>)->Void) -> DataRequest {
return AF.request(route, interceptor: EnvironmentInterceptor())
.responseDecodable (decoder: decoder){ (response: DataResponse<T>) in
completion(response.result)
}

Resources