尝试使用密码授予类型在项目中学习和实施OAuth2流,并且在理解这一点时遇到问题。我从以下方面获取灵感:https://github.com/p2/OAuth2/issues/255。当前设置一直有效,直到显示LoginViewController()然后它有点令人困惑。
我有一个ViewController,可以在viewDidAppear上调用我的LoginService Just for testing purposes
class ViewController: UIViewController {
var loginService: LoginService?
override func viewDidLoad() {
super.viewDidLoad()
loginService = LoginService(clientID: "", clientSecret: "", username: "", password: "")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
loginService?.authorize(presenting: self)
}
}
和LoginService文件:
final class LoginService: OAuth2PasswordGrantDelegate {
public var oauth2: OAuth2PasswordGrant
init(clientID: String, clientSecret: String, username: String, password: String) {
oauth2 = OAuth2PasswordGrant(settings: [
"client_id": clientID,
"client_secret": clientSecret,
"authorize_uri": "",
"token_uri": "",
"grant_type": "password",
"scope": "user",
"keychain": true,
"verbose": true
] as OAuth2JSON)
oauth2.username = username
oauth2.password = password
let sessionManager = SessionManager()
let retrier = OAuth2Service(oauth2: oauth2)
sessionManager.retrier = retrier
sessionManager.adapter = retrier
alamoFireService = sessionManager
oauth2.delegate = self
}
public func authorize(presenting view: UIViewController) {
oauth2.authConfig.authorizeContext = view
oauth2.logger = OAuth2DebugLogger(.trace)
oauth2.verbose = true
if oauth2.isAuthorizing {
oauth2.abortAuthorization()
return
}
if let view = view as? OAuth2PasswordGrantDelegate {
oauth2.delegate = view
}
// IS THIS THE CORRECT WAY?
alamoFireService?.request(APIRequest.Login.path).validate().responseJSON { response in
debugPrint(response)
if let response = response.result.value as? [String:Any] {
// Will be access token + refresh token here!
print(response)
} else {
print(OAuth2Error.generic("\(response)"))
}
}
oauth2.authorizeEmbedded(from: view) { (authParams, error) in
if let _ = authParams {
print(authParams)
// TODO: - Set keychain values here
} else {
print("Authorization error: \(String(describing: error?.description))")
}
}
}
public func loginController(oauth2: OAuth2PasswordGrant) -> AnyObject {
if let vc = oauth2.authConfig.authorizeContext as? UIViewController {
vc.present(LoginViewController(), animated: true)
}
return LoginViewController()
}
}
我在何时通过用户输入的凭据,我是否需要手动使用Alamofire进行网络呼叫以获取访问+刷新令牌,还是由OAuth2PasswordGrantDelegate
处理?
谢谢
我也无法在网上找到这个流程的例子,因此可能会对一群开发者有用。
更新
我已经对文档进行了很好的扫描,并且方法tryCredentials
采用了用户名+密码。已将其设置为在登录按钮内调用,它可以正常工作。这是正确的方法吗?