Created
December 20, 2017 17:23
-
-
Save ahelland/ae40c776b789b4b65371ae1a5ab18ba6 to your computer and use it in GitHub Desktop.
Azure Function for acquiring a token from Azure AD, and subsequently use this for auth towards Azure API Management
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using Newtonsoft.Json; | |
public static void Run(string input, TraceWriter log) | |
{ | |
log.Info($"C# manually triggered function called with input: {input}"); | |
var apimUrl = " https://contosio.azure-api.net/foo/messages"; | |
var content = "{\"on\":true, \"sat\":254, \"bri\":254, \"hue\":10000}"; | |
var AADToken = getToken().Result; | |
HttpClient Client = new HttpClient(); | |
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AADToken); | |
Client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key","subKey"); | |
var foo = Client.PostAsync(apimUrl, new StringContent(content.ToString())).Result; | |
log.Info($"result: {foo}"); | |
} | |
public static async Task<string> getToken() | |
{ | |
var domain = "contoso.onmicrosoft.com"; | |
var clientId = "id"; | |
var clientSecret = "secret"; | |
var resource = "app uri"; | |
HttpClient client = new HttpClient(); | |
string requestUrl = $"https://login.microsoftonline.com/{domain}/oauth2/token"; | |
string request_content = $"grant_type=client_credentials&resource={resource}&client_id={clientId}&client_secret={clientSecret}&scope=openid"; | |
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl); | |
try | |
{ | |
request.Content = new StringContent(request_content, Encoding.UTF8, "application/x-www-form-urlencoded"); | |
} | |
catch (Exception x) | |
{ | |
var msg = x.Message; | |
} | |
HttpResponseMessage response = await client.SendAsync(request); | |
string responseString = await response.Content.ReadAsStringAsync(); | |
GenericToken token = JsonConvert.DeserializeObject<GenericToken>(responseString); | |
var at = token.access_token; | |
return at; | |
} | |
internal class GenericToken | |
{ | |
public string token_type { get; set; } | |
public string scope { get; set; } | |
public string resource { get; set; } | |
public string access_token { get; set; } | |
public string refresh_token { get; set; } | |
public string id_token { get; set; } | |
public string expires_in { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment