Zig Requires Chilkat v11.0.0+
Zig
AzureWebsites OAuth2 Password Flow
See more OAuth2 Examples
Demonstrates how to do OAuth 2.0 password flow for azurewebsites.net.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const http = try chilkat.Http.init();
defer http.deinit();
const req = try chilkat.HttpRequest.init();
defer req.deinit();
req.setHttpVerb("POST");
req.setPath("/token");
req.setContentType("application/x-www-form-urlencoded");
req.addParam("grant_type", "password");
req.addParam("username", "your_username");
req.addParam("password", "your_password");
const token_endpoint = "https://your_api.azurewebsites.net/token";
const resp = try chilkat.HttpResponse.init();
defer resp.deinit();
http.httpReq(token_endpoint, req, resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
const sb_response_body = try chilkat.StringBuilder.init();
defer sb_response_body.deinit();
resp.getBodySb(sb_response_body) catch {};
const j_resp = try chilkat.JsonObject.init();
defer j_resp.deinit();
j_resp.loadSb(sb_response_body) catch {};
j_resp.setEmitCompact(false);
std.debug.print("Response Body:\n", .{});
std.debug.print("{s}\n", .{try j_resp.emit(alloc)});
// 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 resp_status_code: i32 = resp.getStatusCode();
std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
if (resp_status_code >= 400) {
std.debug.print("Response Header:\n", .{});
std.debug.print("{s}\n", .{try resp.getHeader(alloc)});
std.debug.print("Failed.\n", .{});
return;
}
// ----------------------------------
// Use the OAuth2 token in a request.
// For example...
const sb_xml = try chilkat.StringBuilder.init();
defer sb_xml.deinit();
sb_xml.loadFile("c:/someDir/someXmlFile.xml", "utf-8") catch {
std.debug.print("Failed to load the XML file.\n", .{});
return;
};
// Get the OAuth2 token and use it for authentication
http.setAuthToken(try j_resp.stringOf(alloc, "token"));
const dest_url = "https://your_api.azurewebsites.net/destinationUrl";
http.httpSb("POST", dest_url, sb_xml, "utf-8", "application/xml", resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
resp_status_code = resp.getStatusCode();
std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
if (resp_status_code >= 400) {
std.debug.print("Response Header:\n", .{});
std.debug.print("{s}\n", .{try resp.getHeader(alloc)});
std.debug.print("Failed.\n", .{});
return;
}
// Examine the response body
std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});
}