2017-02-17 41 views
1

我正在使用Auth0 SDK版本1.1.0。我正在使用openid名稱電子郵件offline_access範圍。我成功獲取成功響應中的憑證對象。但憑證的expiresIn對象始終爲零。Auth0憑證對象的過期日期屬性始終爲零

var parameters = [String: String]() 
parameters["deviceToken"] = "This is a device token from iOS simulator" 
parameters["device"]  = UIDevice.current.identifierForVendor?.description ?? UIDevice.current.name 

Auth0.authentication().login(usernameOrEmail: usernameField.text!, password: passwordField.text!, 
          multifactorCode: nil, connection: "Username-Password-Authentication", 
          scope: "openid name email offline_access", 
          parameters: parameters).start({ (result) in 
           switch result { 
           case .success(let credentials): 
            WSDataManger.sharedInstance.saveCredentials(credentials: credentials) 
            print("credentail expire date is \(credentials.expiresIn)") 

           case .failure(let error): 
            print("Failed to login: \(error.localizedDescription)") 


          }) 
} 

如何獲取expiresIn date?

+0

嗨,你找到任何解決方案嗎? – EderYif

+0

@EderYif請檢查解決方案。 –

回答

1

方法1: 您可以解碼idToken,你會得到的expiat值。 expires_in可以通過JWT的exp和iat聲明之間的差異來計算。

/// Decode the JWT token 
func decodeJwtToken() -> String? { 

    let tokenInfoArray = self.components(separatedBy: ".") 
    if tokenInfoArray.count >= 2 { 
     // First object array contain {"typ":"JWT","alg":"HS256"} 
     //Second Object is required information 
     let encodedBase64String = tokenInfoArray[1].base64String; 
     guard let data = Data(base64Encoded: encodedBase64String, options: Data.Base64DecodingOptions(rawValue: 0)) else { 
      return nil 
     } 

     guard let decodedString = String(data: data, encoding: .utf8) else { return nil } 
     //remove null terminator Occurrences. 
     let nullTerminatedString = decodedString.replacingOccurrences(of: "\0", with: "") 
     //remove whitespace Occurrences. 
     let formattedString = nullTerminatedString.replacingOccurrences(of: " ", with: "") 
     return formattedString 
    } 
    return nil 
} 

方法2:您可以使用Auth0代表團API來獲取expires_in並將其存儲在默認或Auth0鑰匙扣。

// Renewing the expired token 
func renewToken() { 
    let payload = [ 
     "refresh_token" : defaults.value(forKey: "refresh_token"), 
     "id_token" : defaults.value(forKey: "id_token"), 
     "scope": "openid name email offline_access" ] 
    Auth0.authentication().delegation(withParameters: payload).start { (result) in 
     print(result) 
     switch result { 
     case .success(let credentials): 
      if let value = credentials["id_token"] { 
       defaults.setValue(value, forKey: "id_token") 
      } 
      if let value = credentials["expires_in"] as? Double { 
       print("expires_in timestamp \(value)") 
       //Calculate timestamp to date format. 
      } 
      defaults.synchronize() 
     case .failure(let error): 
       //Handle Error 
       print(error) 
     } 
    } 
} 
相關問題