I have an application that authenticates on a website without any API, just to the login page and then save the cookies for next requests.

The problem is what happens when the session or the cookies has expired, the website redirects to /login with HTTP 200. (I don't have access to website.)

I'm using Alamofire library, it includes "Adapting and Retrying Requests" and its good for things like OAuth, but not for my case, because RequestRetrier only is called on some HTTP error codes, and i always receive OK 200.

I only can catch the redirect url and if it contains "/login" then i know the session has expired.

I tried using taskWillPerformHTTPRedirection something like this

delegate.taskWillPerformHTTPRedirection = { session, task, response, request in

var f_request = request  

if (request.url!.absoluteString.contains("login.jsp")) {

  loginAgain(){
   // After successfully login return the original request.
    f_request = task.originalRequest
 }

return f_request
}

But of course the login request is asynchronous call, so the login is made after the original request.

How should I do it? Synchronous login call? i'm missing some in Alamofire?

1 Answers

0
Vincen On

Okay, I did not know the existence of: "taskWillPerformHTTPRedirectionWithCompletion"

so.. problem solved.

delegate.taskWillPerformHTTPRedirectionWithCompletion = { session, task, response, request, completion in

 if(needLoginLogic){

  login_bg(){ (result) in
    switch result {
     case .success:
      // Make the original request inteast of "/login" request
      completion(task.originalRequest)
      break

     case .failure(let error):
      // Catch error later.
      completion(request)
      break
    }

  }

 }else{
 // Just make the request
 completion(request)
 }

}