我能够进行身份验证,但仍无法使登录工作。登录请求会抛出一个通用的500状态码作为响应。我已经尝试使用session.dataTask()代替session.uploadTask()进行登录,但这没有帮助。
我正在尝试将python中的工作代码移植到可可应用程序中-
How can I log in to morningstar.com without using a headless browser such as selenium?
func mornLogin(){
let authUrl = URL(string: "https://sso.morningstar.com/sso/json/msusers/authenticate")
let loginUrl = URL(string: "https://www.morningstar.com/api/v2/user/login")
let userName = "username"
let passWord = "password"
// Configure URL Session
let session = URLSession(configuration: URLSessionConfiguration.default)
// Prepare Authentication URL Request
var authRequest = URLRequest(url: authUrl!)
authRequest.httpMethod = "POST"
authRequest.addValue("https://www.morningstar.com/members/login.html", forHTTPHeaderField: "Referer")
authRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
authRequest.addValue(userName, forHTTPHeaderField: "X-OpenAM-Username")
authRequest.addValue(passWord, forHTTPHeaderField: "X-OpenAM-Password")
authRequest.addValue("https://www.morningstar.com", forHTTPHeaderField: "Origin")
let authTask = session.dataTask(with: authRequest) { (data, response, error) in
if let response = response, let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode == 200 {
print("Authentication successful!")
// Prepare Login URL Request
struct loginData: Codable {
var productCode: String
var rememberMe: Bool
}
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonBody = try! encoder.encode(loginData(productCode: "DOT_COM", rememberMe: false))
var loginRequest = URLRequest(url: loginUrl!)
loginRequest.httpBody = jsonBody
loginRequest.httpMethod = "POST"
let loginTask = session.uploadTask(with: loginRequest, from: jsonBody) {
(data, response, error) in
if let response = response, let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode == 200 {
print("Login successful!")
}
else
{
print("Login error, response = \(String(describing: response))")
}
}
loginTask.resume()
}
else
{
print("Authentication error, response = \(String(describing: response))")
}
}
authTask.resume()
}