NSURLSession Authentication

烂漫一生 提交于 2019-11-29 18:06:24

There are 2 ways to sign in to a website: HTTP Authorization and form. Most website uses the later, more user-friendly login form. HTTP Authorization is only used when the website expects to interact with a user program (no, browsers don't count here).

Before you code, you need to scout the website for what form data it sends, as knowing is half the battle:

  1. Visit the school website and press Cmd + Opt + C to open the Developer's Console.
  2. Click the Network tab.
  3. Do not close this console. Go back to the website and enter your username and password as usual.

Observe what data the page sends:

In plain text:

checkCookiesEnabled         true
checkMobileDevice           false
checkStandaloneMode         false
checkTabletDevice           false
portalAccountUsername       email
portalAccountPassword       password
portalAccountUsernameLabel

So the username is delivered in a field called portalAccountUsername and password in portalAccountPassword. The other fields may or may not be important.

And now you can write your code:

@IBAction func login(sender: AnyObject) {
    let url = NSURL(string: "https://hac.chicousd.org/LoginParent.aspx")!

    // The form parameters
    let parameters = [
        "checkCookiesEnabled": "true",
        "checkMobileDevice": "false",
        "checkStandaloneMode": "false",
        "checkTabletDevice": "false",
        "portalAccountUsername": "username",
        "portalAccountPassword": "password"
    ]

    let bodyString = parameters
                        .map { $0 + "=" + $1 }
                        .joinWithSeparator("&")
                        .stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())!


    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil else {
            print(error?.localizedDescription)
            return
        }
        guard let data = data else {
            print("empty data")
            return
        }

        // This is the HTML source of the landing page after login
        let html = String(data: data, encoding: NSUTF8StringEncoding)
    }
    task.resume()
}

For some reasons, I couldn't make the request until I disabled App Transport Security. Maybe resources on that website come from non-HTTPS domains.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!