Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

AzureWebsites OAuth2 Password Flow

See more OAuth2 Examples

Demonstrates how to do OAuth 2.0 password flow for azurewebsites.net.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    let http = CkoHttp()!

    let req = CkoHttpRequest()!
    req.httpVerb = "POST"
    req.path = "/token"
    req.contentType = "application/x-www-form-urlencoded"
    req.addParam(name: "grant_type", value: "password")
    req.addParam(name: "username", value: "your_username")
    req.addParam(name: "password", value: "your_password")

    var tokenEndpoint: String? = "https://your_api.azurewebsites.net/token"

    let resp = CkoHttpResponse()!
    success = http.httpReq(url: tokenEndpoint, request: req, response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    let sbResponseBody = CkoStringBuilder()!
    resp.getBodySb(sb: sbResponseBody)
    let jResp = CkoJsonObject()!
    jResp.loadSb(sb: sbResponseBody)
    jResp.emitCompact = false

    print("Response Body:")
    print("\(jResp.emit()!)")

    //  Sample JSON response:

    //  {
    //    "access_token": "NQGHn ... xTS",
    //    "token_type": "bearer",
    //    "expires_in": 1209599,
    //    "userName": "your_username",
    //    ".issued": "Mon, 27 Apr 2020 23:49:35 GMT",
    //    ".expires": "Mon, 11 May 2020 23:49:35 GMT"
    //  }

    var respStatusCode: Int = resp.statusCode.intValue
    print("Response Status Code = \(respStatusCode)")
    if respStatusCode >= 400 {
        print("Response Header:")
        print("\(resp.header!)")
        print("Failed.")
        return
    }

    //  ----------------------------------
    //  Use the OAuth2 token in a request.
    //  For example...

    let sbXml = CkoStringBuilder()!
    success = sbXml.loadFile(path: "c:/someDir/someXmlFile.xml", charset: "utf-8")
    if success == false {
        print("Failed to load the XML file.")
        return
    }

    //  Get the OAuth2 token and use it for authentication
    http.authToken = jResp.string(of: "token")

    var destUrl: String? = "https://your_api.azurewebsites.net/destinationUrl"
    success = http.httpSb(verb: "POST", url: destUrl, sb: sbXml, charset: "utf-8", contentType: "application/xml", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    respStatusCode = resp.statusCode.intValue
    print("Response Status Code = \(respStatusCode)")
    if respStatusCode >= 400 {
        print("Response Header:")
        print("\(resp.header!)")
        print("Failed.")
        return
    }

    //  Examine the response body
    print("\(resp.bodyStr!)")

}