Sample code for 30+ languages & platforms
Unicode C++

AzureWebsites OAuth2 Password Flow

See more OAuth2 Examples

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

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkHttpW.h>
#include <CkHttpRequestW.h>
#include <CkHttpResponseW.h>
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkHttpW http;

    CkHttpRequestW req;
    req.put_HttpVerb(L"POST");
    req.put_Path(L"/token");
    req.put_ContentType(L"application/x-www-form-urlencoded");
    req.AddParam(L"grant_type",L"password");
    req.AddParam(L"username",L"your_username");
    req.AddParam(L"password",L"your_password");

    const wchar_t *tokenEndpoint = L"https://your_api.azurewebsites.net/token";

    CkHttpResponseW resp;
    success = http.HttpReq(tokenEndpoint,req,resp);
    if (success == false) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    CkStringBuilderW sbResponseBody;
    resp.GetBodySb(sbResponseBody);
    CkJsonObjectW jResp;
    jResp.LoadSb(sbResponseBody);
    jResp.put_EmitCompact(false);

    wprintf(L"Response Body:\n");
    wprintf(L"%s\n",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"
    // }

    int respStatusCode = resp.get_StatusCode();
    wprintf(L"Response Status Code = %d\n",respStatusCode);
    if (respStatusCode >= 400) {
        wprintf(L"Response Header:\n");
        wprintf(L"%s\n",resp.header());
        wprintf(L"Failed.\n");
        return;
    }

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

    CkStringBuilderW sbXml;
    success = sbXml.LoadFile(L"c:/someDir/someXmlFile.xml",L"utf-8");
    if (success == false) {
        wprintf(L"Failed to load the XML file.\n");
        return;
    }

    // Get the OAuth2 token and use it for authentication
    http.put_AuthToken(jResp.stringOf(L"token"));

    const wchar_t *destUrl = L"https://your_api.azurewebsites.net/destinationUrl";
    success = http.HttpSb(L"POST",destUrl,sbXml,L"utf-8",L"application/xml",resp);
    if (success == false) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    respStatusCode = resp.get_StatusCode();
    wprintf(L"Response Status Code = %d\n",respStatusCode);
    if (respStatusCode >= 400) {
        wprintf(L"Response Header:\n");
        wprintf(L"%s\n",resp.header());
        wprintf(L"Failed.\n");
        return;
    }

    // Examine the response body
    wprintf(L"%s\n",resp.bodyStr());
    }