Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
like image 639
Jayprakash Singh Avatar asked Sep 04 '17 06:09

Jayprakash Singh


People also ask

How does Swift handle token expiration?

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.

How do I handle expired access tokens?

Token Refresh Handling: Method 1 convert expires_in to an expire time (epoch, RFC-3339/ISO-8601 datetime, etc.) store the expire time. on each resource request, check the current time against the expire time and make a token refresh request before the resource request if the access_token has expired.

What happens when access token expires?

When the access token expires, the application will be forced to make the user sign in again, so that you as the service know the user is continually involved in re-authorizing the application.

How do I know if my refresh token is expired?

If you look in the dashboard application settings, you can see the Refresh Token expiration time. By default, it is 720 hours (2592000 seconds). Since the error message says inavlid_grant , it may be possible that the application is not configured to accept Refresh Token grants.


2 Answers

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.

like image 54
Ravi B Avatar answered Oct 29 '22 02:10

Ravi B


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)
            }
      }
}
like image 32
foram Avatar answered Oct 29 '22 00:10

foram