Skip to content

Instantly share code, notes, and snippets.

@buchizo buchizo/program.cs

Last active Apr 29, 2019
Embed
What would you like to do?
call Azure ARM REST API sample (for .NET Framework)
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography; //add System.Security.Cryptography.ProtectedData nuget package
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private const string ARMClientID = "1950a258-227b-4e31-a9cf-717495945fc2"; // <- this is Azure PowerShell client id
private const string AppRedirectUrl = "urn:ietf:wg:oauth:2.0:oob"; // <- this is Azure PowerShell redirect url
static async Task Main(string[] args)
{
var authContextURL = "https://login.windows.net/common/";
var authenticationContext = new AuthenticationContext(authContextURL, new FileCache());
var token = await authenticationContext.AcquireTokenAsync(
resource: "https://management.azure.com/",
clientId: ARMClientID,
redirectUri: new Uri(AppRedirectUrl),
parameters: new PlatformParameters(PromptBehavior.Auto));
// call to Azure ARM REST API using user token
var req = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://management.azure.com/providers/Microsoft.Features/operations?api-version=2015-12-01")
};
req.Headers.Add("Authorization", token.CreateAuthorizationHeader());
var client = new HttpClient();
var res = await client.SendAsync(req);
Console.WriteLine("-----------------------");
Console.WriteLine(res.StatusCode);
var body = await res.Content.ReadAsStringAsync();
Console.WriteLine(body);
Console.WriteLine("Hit any key.");
Console.ReadKey();
}
}
// see also : https://github.com/Azure-Samples/active-directory-dotnet-native-headless/tree/master/TodoListClient
public class FileCache : TokenCache
{
public string CacheFilePath;
private static readonly object FileLock = new object();
// Initializes the cache against a local file.
// If the file is already present, it loads its content in the ADAL cache
public FileCache(string filePath = @".\TokenCache.dat")
{
CacheFilePath = filePath;
this.AfterAccess = AfterAccessNotification;
this.BeforeAccess = BeforeAccessNotification;
lock (FileLock)
{
this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null);
}
}
// Empties the persistent store.
public override void Clear()
{
base.Clear();
File.Delete(CacheFilePath);
}
// Triggered right before ADAL needs to access the cache.
// Reload the cache from the persistent store in case it changed since the last access.
void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
lock (FileLock)
{
this.Deserialize(File.Exists(CacheFilePath) ? ProtectedData.Unprotect(File.ReadAllBytes(CacheFilePath), null, DataProtectionScope.CurrentUser) : null);
}
}
// Triggered right after ADAL accessed the cache.
void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if the access operation resulted in a cache update
if (this.HasStateChanged)
{
lock (FileLock)
{
// reflect changes in the persistent store
File.WriteAllBytes(CacheFilePath, ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser));
// once the write operation took place, restore the HasStateChanged bit to false
this.HasStateChanged = false;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.