Sample code for 30+ languages & platforms
Objective-C

AzureWebsites OAuth2 Password Flow

See more OAuth2 Examples

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

Chilkat Objective-C Downloads

Objective-C
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <NSString.h>
#import <CkoHttpResponse.h>
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>

BOOL success = NO;

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

CkoHttp *http = [[CkoHttp alloc] init];

CkoHttpRequest *req = [[CkoHttpRequest alloc] init];
req.HttpVerb = @"POST";
req.Path = @"/token";
req.ContentType = @"application/x-www-form-urlencoded";
[req AddParam: @"grant_type" value: @"password"];
[req AddParam: @"username" value: @"your_username"];
[req AddParam: @"password" value: @"your_password"];

NSString *tokenEndpoint = @"https://your_api.azurewebsites.net/token";

CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
success = [http HttpReq: tokenEndpoint request: req response: resp];
if (success == NO) {
    NSLog(@"%@",http.LastErrorText);
    return;
}

CkoStringBuilder *sbResponseBody = [[CkoStringBuilder alloc] init];
[resp GetBodySb: sbResponseBody];
CkoJsonObject *jResp = [[CkoJsonObject alloc] init];
[jResp LoadSb: sbResponseBody];
jResp.EmitCompact = NO;

NSLog(@"%@",@"Response Body:");
NSLog(@"%@",[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.StatusCode intValue];
NSLog(@"%@%d",@"Response Status Code = ",respStatusCode);
if (respStatusCode >= 400) {
    NSLog(@"%@",@"Response Header:");
    NSLog(@"%@",resp.Header);
    NSLog(@"%@",@"Failed.");
    return;
}

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

CkoStringBuilder *sbXml = [[CkoStringBuilder alloc] init];
success = [sbXml LoadFile: @"c:/someDir/someXmlFile.xml" charset: @"utf-8"];
if (success == NO) {
    NSLog(@"%@",@"Failed to load the XML file.");
    return;
}

//  Get the OAuth2 token and use it for authentication
http.AuthToken = [jResp StringOf: @"token"];

NSString *destUrl = @"https://your_api.azurewebsites.net/destinationUrl";
success = [http HttpSb: @"POST" url: destUrl sb: sbXml charset: @"utf-8" contentType: @"application/xml" response: resp];
if (success == NO) {
    NSLog(@"%@",http.LastErrorText);
    return;
}

respStatusCode = [resp.StatusCode intValue];
NSLog(@"%@%d",@"Response Status Code = ",respStatusCode);
if (respStatusCode >= 400) {
    NSLog(@"%@",@"Response Header:");
    NSLog(@"%@",resp.Header);
    NSLog(@"%@",@"Failed.");
    return;
}

//  Examine the response body
NSLog(@"%@",resp.BodyStr);