Delphi ActiveX Requires Chilkat v11.0.0+
Delphi ActiveX
AzureWebsites OAuth2 Password Flow
See more OAuth2 Examples
Demonstrates how to do OAuth 2.0 password flow for azurewebsites.net.Chilkat Delphi ActiveX Downloads
var
success: Integer;
http: TChilkatHttp;
req: TChilkatHttpRequest;
tokenEndpoint: WideString;
resp: TChilkatHttpResponse;
sbResponseBody: TChilkatStringBuilder;
jResp: TChilkatJsonObject;
respStatusCode: Integer;
sbXml: TChilkatStringBuilder;
destUrl: WideString;
begin
success := 0;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
http := TChilkatHttp.Create(Self);
req := TChilkatHttpRequest.Create(Self);
req.HttpVerb := 'POST';
req.Path := '/token';
req.ContentType := 'application/x-www-form-urlencoded';
req.AddParam('grant_type','password');
req.AddParam('username','your_username');
req.AddParam('password','your_password');
tokenEndpoint := 'https://your_api.azurewebsites.net/token';
resp := TChilkatHttpResponse.Create(Self);
success := http.HttpReq(tokenEndpoint,req.ControlInterface,resp.ControlInterface);
if (success = 0) then
begin
Memo1.Lines.Add(http.LastErrorText);
Exit;
end;
sbResponseBody := TChilkatStringBuilder.Create(Self);
resp.GetBodySb(sbResponseBody.ControlInterface);
jResp := TChilkatJsonObject.Create(Self);
jResp.LoadSb(sbResponseBody.ControlInterface);
jResp.EmitCompact := 0;
Memo1.Lines.Add('Response Body:');
Memo1.Lines.Add(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"
// }
respStatusCode := resp.StatusCode;
Memo1.Lines.Add('Response Status Code = ' + IntToStr(respStatusCode));
if (respStatusCode >= 400) then
begin
Memo1.Lines.Add('Response Header:');
Memo1.Lines.Add(resp.Header);
Memo1.Lines.Add('Failed.');
Exit;
end;
// ----------------------------------
// Use the OAuth2 token in a request.
// For example...
sbXml := TChilkatStringBuilder.Create(Self);
success := sbXml.LoadFile('c:/someDir/someXmlFile.xml','utf-8');
if (success = 0) then
begin
Memo1.Lines.Add('Failed to load the XML file.');
Exit;
end;
// Get the OAuth2 token and use it for authentication
http.AuthToken := jResp.StringOf('token');
destUrl := 'https://your_api.azurewebsites.net/destinationUrl';
success := http.HttpSb('POST',destUrl,sbXml.ControlInterface,'utf-8','application/xml',resp.ControlInterface);
if (success = 0) then
begin
Memo1.Lines.Add(http.LastErrorText);
Exit;
end;
respStatusCode := resp.StatusCode;
Memo1.Lines.Add('Response Status Code = ' + IntToStr(respStatusCode));
if (respStatusCode >= 400) then
begin
Memo1.Lines.Add('Response Header:');
Memo1.Lines.Add(resp.Header);
Memo1.Lines.Add('Failed.');
Exit;
end;
// Examine the response body
Memo1.Lines.Add(resp.BodyStr);