我使用的是Auth0 SDK 1.1.0版。我正在使用 openid name email offline_access 范围。我在成功响应中成功获取凭证对象。但是凭证的到期对象总是为零。
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)")
})
}
如何获得过期日期?
答案 0 :(得分:1)
方法1 :
您可以解码idToken,您将获得exp
和iat
值。 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 Keychain中。
// 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)
}
}
}