Sample code for 30+ languages & platforms
Dart 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 Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

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

  final http = CkHttp();

  final req = CkHttpRequest();
  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');

  final tokenEndpoint = 'https://your_api.azurewebsites.net/token';

  final resp = CkHttpResponse();
  try {
    http.httpReq(tokenEndpoint, req, resp);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final sbResponseBody = CkStringBuilder();
  resp.getBodySb(sbResponseBody);
  final jResp = CkJsonObject();
  jResp.loadSb(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 = resp.statusCode;
  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...

  final sbXml = CkStringBuilder();
  try {
    sbXml.loadFile('c:/someDir/someXmlFile.xml', 'utf-8');
  } on ChilkatException {
    print('Failed to load the XML file.');
    return;
  }

  // Get the OAuth2 token and use it for authentication
  http.authToken = jResp.stringOf('token');

  final destUrl = 'https://your_api.azurewebsites.net/destinationUrl';
  try {
    http.httpSb('POST', destUrl, sbXml, 'utf-8', 'application/xml', resp);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  respStatusCode = resp.statusCode;
  print('Response Status Code = $respStatusCode');
  if (respStatusCode >= 400) {
    print('Response Header:');
    print(resp.header);
    print('Failed.');
    return;
  }

  // Examine the response body
  print(resp.bodyStr);
}