【发布时间】:2021-03-05 17:10:23
【问题描述】:
我正在使用 AppAuth library 获取 Gmail API 的访问令牌。我已经成功地创建了一个身份验证会话,并使用检索到的令牌稍后获取电子邮件。
在我的AppDelegate 中有两个变量:
var currentAuthorizationFlow: OIDExternalUserAgentSession?
var authState: OIDAuthState?
在我的SignInViewController 中,我有以下代码用于执行授权流程:
@objc func startAuthFlow() {
Analytics.logEvent("auth_started", parameters: nil)
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 kRedirectURI: String = "com.googleusercontent.apps.someNumber:/oauthredirect";
guard let redirectURI = URL(string: kRedirectURI) else {
return
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// builds authentication request
let request = OIDAuthorizationRequest(configuration: configuration,
clientId: "myID",
clientSecret: nil,
scopes: ["https://mail.google.com/"],
redirectURL: redirectURI,
responseType: OIDResponseTypeCode,
additionalParameters: nil)
// performs authentication request
print("Initiating authorization request with scope: \(request.scope ?? "nil")")
appDelegate.currentAuthorizationFlow =
OIDAuthState.authState(byPresenting: request, presenting: self) { authState, error in
if let authState = authState {
print("Got authorization tokens. Access token: " +
"\(authState.lastTokenResponse?.accessToken ?? "nil")")
A0SimpleKeychain().setString((authState.lastTokenResponse?.accessToken)!, forKey: "auth0-user-jwt")
A0SimpleKeychain().setString((authState.lastTokenResponse?.refreshToken)!, forKey: "auth0-user-jwt-refresh")
EmailFetcher.shared.setupEmailSession(token: (authState.lastTokenResponse?.accessToken)!)
} else {
print("Authorization error: \(error?.localizedDescription ?? "Unknown error")")
}
}
}
然后我成功保存了令牌和刷新令牌。
我看到OIDAuthState 有一个tokenRefreshRequest() 方法,但我的理解是您需要传入刷新令牌才能获得一个新的、新鲜的令牌,对吗?使用 AppAuth 实现这一点缺少什么?
【问题讨论】:
标签: ios swift oauth-2.0 gmail-api appauth