Swift Alamofire + OAuth2 refresh token - ios

Currently learning how to add OAuth2 via Alamofire and getting confused. I'm using the password grant type and when a request fails I understand that the retrier kicks in and requests a token refresh. The confusing part is which one do I use?
Alamofire 4 using p2/OAuth2
Alamofire RequestRetrier + Request Adapter
The first one uses less code so unsure if its all the functionality I need. I also can't find a concrete example explaining this process.
I believe the following performs the refresh request?
private func refreshTokens(completion: RefreshCompletion) {
guard !isRefreshing else { return }
isRefreshing = true
let urlString = "\(baseURLString)/oauth2/token"
let parameters: [String: Any] = [
"access_token": accessToken,
"refresh_token": refreshToken,
"client_id": clientID,
"grant_type": "refresh_token"
]
sessionManager.request(urlString, withMethod: .post, parameters: parameters, encoding: .json).responseJSON { [weak self] response in
guard let strongSelf = self else { return }
if let json = response.result.value as? [String: String] {
completion(true, json["access_token"], json["refresh_token"])
} else {
completion(false, nil, nil)
}
strongSelf.isRefreshing = false
}
}
This is then passed back to adapt the previous request?
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: #escaping RequestRetryCompletion) {}
Is this the correct way of implementing this?
Thanks

Related

How to refresh Api authorization token using Alamofire & rxSwift?

I try to manage rxswift & Alamofire to get response.
These functions get response successfully when token is not expired.
But when the token is expired, I don't know how to refresh token and then retry to get response using new token.
What should I do to refresh token and retry?
I also read Alamofire documents, and I find "RequestAdapter" and "RequestRetrier".
Should I use RequestAdapter & RequestRetrier in my case?
But I dont know how to use them in my "getRequestJSON" function,
or have any good idea to refresh token and retry.
Thanks.
func get(_ callback: #escaping (JSON) -> Void) {
let url = "http://106.xx.xxx.xxx/user"
self.getRequestJSON( .get, url: url, params: [:], callback: { json in
callback(json)
})
}
func getRequestJSON(_ method: Alamofire.HTTPMethod, url:String, params:[String:Any] = [:], callback: #escaping (JSON) -> Void) {
var headers:[String:String] = [String:String]()
if token.isEmpty == false {
headers["Authorization"] = "Bearer \(token)"
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = timeout
_ = SessionManager(configuration: configuration)
.rx.responseJSON(method,
url,
parameters: params,
encoding: ((method == .get) ? URLEncoding.default : JSONEncoding.default),
headers: headers)
.subscribeOn(SerialDispatchQueueScheduler.init(qos: .background))
.subscribe(onNext: { (r, data) in
if r.statusCode == 401 {
//token fail
}
let json = JSON(data)
if json["status"].stringValue == "successful" {
callback(json)
}else {
callback(json)
}
}, onError: { (error) in
callback(JSON(error))
})
.addDisposableTo(ResfulAPIDisposeBag)
}

Swift 3.0 token expire how will be call the token automatically?

Once the token is received, when the token is over, then how can I call the token automatically after the login? on same page
Alamofire.request(urlString, method: .post, parameters: newPost, encoding: JSONEncoding.default)
.responseJSON { response in
if let json = response.result.value as? [String : Any]{
print("JSON: \(json)")
if UserDefaults.standard.bool(forKey: "logged_in") {
Token = json["Token"]! as! String
UserDefaults.standard.set(Token, forKey: "Token")
UserDefaults.standard.synchronize()
}
} else {
print("Did not receive json")
}
//expectation.fulfill()
}
For the Authorisation Token, the ideal practice is from server side they need to check, requested API call have TOKEN is valid or not. And if the token is not matched or expired, they will provide HTTP status code 401, from Mobile side you need to check the status code first and if you found 401 you need to forcefully logout or re login which takes a new token and you can save it in your UserDefaults.
Scenario 1 : You need to tell to backend developer who made your webservice, that he need to check if TOKEN is valid or not. if token is expired he need to give message code or message that "Token has been expired" and you can check in Response if message code is for expired than you need to navigate your Login screen.
This is best practice.
Scenario 2 : If you dont want to Logout from app, and keep app going with new token automatically refresh, tell webservice developer that whenever token will be expired he will return new Token in response field as "Authorization" And from your code side, you need to check in each request whether Authorization contains new token.. if it contains that means you need to replace old token with New one in userdefault.
Below is my code in Swift3 :
func requestApiCall(_ urlString: String, paramData: NSObject, completionHandler: #escaping (NSDictionary?, NSError?) -> ()) {
let token = UserDefaults.standard.object(forKey: “token” as String)
var headersVal = [
"Authorization": "Bearer "+(token as String),
]
Alamofire.request(urlString, method: .post, parameters: paramData as? [String : AnyObject],encoding: JSONEncoding.default, headers: headersVal)
.responseJSON { response in
if let authorization = response.response?.allHeaderFields["Authorization"] as? String {
var newToken : String = authorization
UserDefaults.standard.set(newToken, forKey: "token")
UserDefaults.standard.synchronize()
}
switch response.result {
case .success(let value):
if let res = response.result.value {
let response = res as! NSDictionary
let message = response.object(forKey: "message")!
print(message)
if message as! String == "Token has been expired"
{
self.showLoginScreen()
}
}
completionHandler(value as? NSDictionary, nil)
case .failure(let error):
if error._code == -1001 {
print("timeout")
}
completionHandler(nil, nil)
}
}
}
Call service for new token when token expires is unsecure to your app because if token expires and you call service for new token then anyone can access your app or its data. The better way is to logout/sign out the user and ask him to login again.
but if you want to do so then make a method which is user to get new token and call it once you will get token expire code.
but you need to discuss with your backend developer for this new api and accordingly you can move farther
let me know for help . Thanks
I preferred to use Moya framework (abstraction under Alamofire) with PromiseKit. It makes easier write async code and create dependencies between parts. I wrapped all business logic for sending requests in the class. The main function of the request (public func register(device: String, type: String) -> Promise<Device>) returns Promise object. In the recover block I validate error code and if needed I refresh token and repeat failed request. Code example below:
public protocol HttpClientInterface {
...
func register(device: String, type: String) -> Promise<Device>
...
}
public func register(device: String, type: String) -> Promise<Device> {
return self.sendRegisterRequest(with: device, type: type)
.then {
self.parseRegister(response: $0)
}
.recover { lerror -> Promise<Device> in
guard let error = lerror as? HttpClientError,
case .server(let value) = error,
value == ServerError.notAuthenticated,
let refreshToken = self.credentialsStore.get()?.token?.refreshToken else {
throw lerror
}
return self.sendRefreshSessionRequest(operatorId: self.operatorId, refreshToken: refreshToken)
.then { data -> Promise<AuthToken> in
return self.parseRefreshSession(data)
}
.then { token -> Promise<Device> in
self.credentialsStore.update(token: token)
return self.register(device: device, type: type)
}
.catch { error in
if let myError = error as? HttpClientError,
case .server(let value) = httpError,
value == ServerError.notAuthenticated {
self.credentialsStore.accessDenied()
}
}
}
}
func sendRegisterRequest(with name: String, type: String) -> Promise<Data> {
return Promise { fulfill, reject in
self.client.request(.register(device: name, type: type)) {
self.obtain(result: $0,
successStatusCodes: [200, 201],
fulfill: fulfill,
reject: reject)
}
}
}
func parseRegister(response data: Data) -> Promise<Device> {
return Promise { fulfill, reject in
if let account = Account(data: data),
let device = account.devices?.last {
fulfill(device)
} else {
reject(HttpClientError.internalError())
}
}
}

Getting OAuth2 access token for Youtube API through Swift

I am working on an iOS mobile application where I need to upload videos using the Youtube Data API. In general, I understand the workflow needed:
1) Send a request to an authentication endpoint using clientId, clientSecret, and other details.
2) The service authenticates the client, and sends back a request to a client-specified callbackURL containing the access token.
3) The client provides the token in the header whenever he/she wants sends future requests.
I've successfully uploaded Youtube videos using node.js script, but I'm having a lot of trouble understanding how to implement this in Swift. In my VideoManagementController, I have a button that triggers the upload of a sample.mp4 file:
let headers = ["Authorization": "Bearer \(self.newToken))"]
let path = Bundle.main.path(forResource: "sample", ofType: ".mp4")
let videodata : NSData = NSData.dataWithContentsOfMappedFile(path!)! as! NSData
print("TOKEN: \(String(describing: token))")
Alamofire.request("https://www.googleapis.com/upload/youtube/v3/videos?part=id", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
print(response)
}
I am attempting to retrieve my access token in the viewDidLoad() stage of the controller:
let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth")
let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token")
let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint!, tokenEndpoint: tokenEndpoint!)
let request = OIDAuthorizationRequest(configuration: configuration, clientId: self.kClientID, scopes: [OIDScopeOpenID, OIDScopeProfile], redirectURL: self.KRedirectURI!, responseType: OIDResponseTypeCode, additionalParameters: nil)
let appDelegate: AppDelegate? = (UIApplication.shared.delegate as? AppDelegate)
print("REACHED")
appDelegate?.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: self, callback: {(_ authState: OIDAuthState?, _ error: Error?) -> Void in
if (authState != nil) {
print("TOKEN: Got authorization tokens. Access token: \(String(describing: authState?.lastTokenResponse?.accessToken))")
self.newToken = authState?.lastTokenResponse?.accessToken
self.authState = authState
}
else {
print("TOKEN: Authorization error: \(String(describing: error?.localizedDescription))")
self.authState = nil
}
})
The issue is that my access token retrieval code essentially hangs and never completes. It reaches the print statement "REACHED" but never comes out of this following portion of code:
appDelegate?.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: self, callback: {(_ authState: OIDAuthState?, _ error: Error?) -> Void in
if (authState != nil) {
print("TOKEN: Got authorization tokens. Access token: \(String(describing: authState?.lastTokenResponse?.accessToken))")
self.newToken = authState?.lastTokenResponse?.accessToken
}
else {
print("TOKEN: Authorization error: \(String(describing: error?.localizedDescription))")
self.authState = nil
}
I do not either get a new token or get the authorization error print out.
I suspect it has something to do with my callbackURL. I don't think Swift knows where to "listen" to get my access token from. A callbackURL endpoint is relatively easy to set up server-side in node.js, for example, but how do I do this in Swift? Or is this even the real issue?
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help , it helps me in using through oauth
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

Swift 3 reusable post method in helper

I am working on swift 3 application and want to build login system using REST API. First I wanted a way to post data to server (PHP + MYSQL) with parameters so I found this post.
HTTP Request in Swift with POST method
Now I wanted place this code in a method as helper so I can utilise this method from anywhere in app. Hence followed this way:
Where to put reusable functions in IOS Swift?
Current code is as follow:
import Foundation
class Helper {
static func postData(resource: String, params: [String: String]) -> [String:String] {
var request = URLRequest(url: URL(string: "http://localsite.dev/api/\(resource)")!)
request.httpMethod = "POST"
var qryString: String = "?key=abcd"
for (paramKey, paramVal) in params {
qryString = qryString.appending("&\(paramKey)=\(paramVal)")
}
request.httpBody = qryString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("Error")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("Error on HTTP")
return
}
let responseString = String(data: data, encoding: .utf8)
print("success and here is returned data \(responseString)")
}
task.resume()
return ["data" : "some data"]
}
}
Call this using
let loginDetails: [String: String] = ["email": emailTxt.text!, "pass": passTxt.text!]
Helper.postData(resource: "login", params: loginDetails)
In above method rather then printing data I want to return data as per below 4 conditions.
1.If error in request data then I want to return as
[“status”: false, “message”: “Something wrong with request”]
2.If error in HTTP request
[“status”: false, “message”: “Resource not found”]
3.If login fail
[“status”: false, “message”: “Wrong login details”]
4.If login success
[“status”: true, “message”: “Login success”]
If you want to use a third party library for handling HTTP request, I strongly recommend Alamofire.
When I wanna handle HTTP requests I usually create a singleton class:
class HttpRequestHelper {
static let shared = HttpRequestHelper()
func post(to url: URL, params: [String: String], headers: [String: String], completion: (Bool, String) -> ()){
//Make the http request
//if u got a successful response
// parse it to JSON and return it via completion handle
completion(true, message)
//if response is not successful
completion(false, message)
}
}
And you can use it everywhere:
class AnotherClass: UIViewController {
HttpRequestHelper.shared.post(to: url, params: [:], header: [:],
completion:{
success, message in
print(success)
print(message)
})
}
To the POST method more reusable and not just specific to an endpoint, I usually make the completion handler params as Bool, JSON. And then I handle the JSON response from wherever I call the method.
Oh and I use SwiftyJson to parse json, it's the simplest.

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