Last active
August 7, 2019 03:12
-
-
Save palmerandy/aa19504cec56a215564a41ea66b733e6 to your computer and use it in GitHub Desktop.
OAuth implementation for Azure Active Directory Authentication of an App Services
This file contains 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
public class AzureAppServiceAuthenticator | |
{ | |
// Found in the Azure Portal > Azure Active Directory > App Registration (matching Function app name) > Overview > Directory (tenant) ID | |
protected internal const string AzureActiveDirectoryTenantId = "abcd1234-abcd-1234-abcd-1234abcd123"; | |
private static readonly HttpClient HttpClient = new HttpClient(); | |
public async Task<string> GetBearerToken() | |
{ | |
var clientId = GetClientId(); | |
var clientSecret = GetClientSecret(); | |
var content = new FormUrlEncodedContent(new[] | |
{ | |
new KeyValuePair<string, string>("client_id", clientId), | |
new KeyValuePair<string, string>("client_secret", clientSecret), | |
new KeyValuePair<string, string>("grant_type", "client_credentials"), | |
new KeyValuePair<string, string>("resource", clientId) | |
}); | |
var response = await HttpClient.PostAsync($"https://login.microsoftonline.com/{AzureActiveDirectoryTenantId}/oauth2/token", content); | |
if (response.IsSuccessStatusCode) | |
{ | |
var authResponse = await response.Content.ReadAsAsync<AuthResponse>(); | |
return authResponse.access_token; | |
} | |
var message = $"Unable to acquire bearer token. Response Status: {response.StatusCode}."; | |
throw new Exception(message); | |
} | |
private static string GetClientId() | |
{ | |
// Found in the Azure Portal > Azure Active Directory > App Registration (matching Function app name) > Overview > Application (client) ID | |
return ConfigurationManager.AppSettings["MyClientId"]; | |
} | |
private static string GetClientSecret() | |
{ | |
// Secret created in the Azure Portal > Azure Active Directory > App Registration (matching Function app name) > Certificates & Secrets > new secret | |
throw new NotImplementedException("return from keyvault after creating"); | |
} | |
public class AuthResponse | |
{ | |
public string token_type { get; set; } | |
public string expires_in { get; set; } | |
public string ext_expires_in { get; set; } | |
public string expires_on { get; set; } | |
public string not_before { get; set; } | |
public string resource { get; set; } | |
public string access_token { get; set; } | |
} | |
} | |
// More information available at https://andypalmer.dev/posts/azure-active-directory-app-service/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment