Skip to content

Instantly share code, notes, and snippets.

@rbrayb
Last active July 8, 2019 23:56
Show Gist options
  • Save rbrayb/5524ead78333b0f4ec14c4a25f9e450f to your computer and use it in GitHub Desktop.
Save rbrayb/5524ead78333b0f4ec14c4a25f9e450f to your computer and use it in GitHub Desktop.
Implementing a client credential flow in ADFS 4.0
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<appSettings>
<add key="ida:ClientId" value="428...2bd"/>
<add key="ida:AppKey" value="nH7...48h_"/>
<add key="todo:TodoListResourceId" value="https://localhost/ToDoListService"/>
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}"/>
<add key="todo:TodoListBaseAddress" value="https://localhost:44321"/>
</appSettings>
</configuration>
/*
The MIT License (MIT)
Copyright (c) 2018 Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// The following using statements were added for this sample.
using System.Globalization;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http;
using System.Threading;
using System.Net.Http.Headers;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Net;
namespace TodoListDaemon
{
class Program
{
//
// The Client ID is used by the application to uniquely identify itself to Azure AD.
// The App Key is a credential used by the application to authenticate to Azure AD.
// The Tenant is the name of the Azure AD tenant in which this application is registered.
// The AAD Instance is the instance of Azure, for example public Azure or Azure China.
// The Authority is the sign-in URL of the tenant.
//
// Changed
//private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
//private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
// Changed
// static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
public static readonly string authority = "https://adfs44.southeastasia.cloudapp.azure.com/adfs";
//
// To authenticate to the To Do list service, the client needs to know the service's App ID URI.
// To contact the To Do list service we need it's URL as well.
//
private static string todoListResourceId = ConfigurationManager.AppSettings["todo:TodoListResourceId"];
private static string todoListBaseAddress = ConfigurationManager.AppSettings["todo:TodoListBaseAddress"];
private static HttpClient httpClient = new HttpClient();
private static AuthenticationContext authContext = null;
private static ClientCredential clientCredential = null;
static void Main(string[] args)
{
//
// Call the To Do service 10 times with short delay between calls.
//
// Changed
authContext = new AuthenticationContext(authority, false);
clientCredential = new ClientCredential(clientId, appKey);
for (int i = 0; i < 2; i++)
{
Thread.Sleep(2000);
PostTodo().Wait();
Thread.Sleep(2000);
GetTodo().Wait();
}
Console.ReadLine();
}
static async Task PostTodo()
{
//
// Get an access token from Azure AD using client credentials.
// If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each.
//
AuthenticationResult result = null;
int retryCount = 0;
bool retry = false;
HttpResponseMessage response = null;
string todoText = "";
do
{
retry = false;
try
{
// ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
result = await authContext.AcquireTokenAsync(todoListResourceId, clientCredential);
}
catch (AdalException ex)
{
if (ex.ErrorCode == "temporarily_unavailable")
{
retry = true;
retryCount++;
Thread.Sleep(3000);
}
Console.WriteLine(
String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n",
DateTime.Now.ToString(),
ex.ToString(),
retry.ToString()));
}
} while ((retry == true) && (retryCount < 3));
if (result == null)
{
Console.WriteLine("Canceling attempt to contact To Do list service.\n");
return;
}
//
// Post an item to the To Do list service.
//
// Add the access token to the authorization header of the request.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
try
{
// Forms encode To Do item and POST to the todo list web api.
string timeNow = DateTime.Now.ToString();
Console.WriteLine("Posting to To Do list at {0}", timeNow);
todoText = "Task at time: " + timeNow;
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("Title", todoText) });
response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content);
}
catch (Exception ex)
{
Console.WriteLine("Exception : " + ex.Message);
}
if (response.IsSuccessStatusCode == true)
{
Console.WriteLine("Successfully posted new To Do item: {0}\n", todoText);
}
else
{
Console.WriteLine("Failed to post a new To Do item\nError: {0}\n", response.ReasonPhrase);
}
}
static async Task GetTodo()
{
//
// Get an access token from Azure AD using client credentials.
// If the attempt to get a token fails because the server is unavailable, retry twice after 3 seconds each.
//
AuthenticationResult result = null;
int retryCount = 0;
bool retry = false;
do
{
retry = false;
try
{
// ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
result = await authContext.AcquireTokenAsync(todoListResourceId, clientCredential);
}
catch (AdalException ex)
{
if (ex.ErrorCode == "temporarily_unavailable")
{
retry = true;
retryCount++;
Thread.Sleep(3000);
}
Console.WriteLine(
String.Format("An error occurred while acquiring a token\nTime: {0}\nError: {1}\nRetry: {2}\n",
DateTime.Now.ToString(),
ex.ToString(),
retry.ToString()));
}
} while ((retry == true) && (retryCount < 3));
if (result == null)
{
Console.WriteLine("Canceling attempt to contact To Do list service.\n");
return;
}
//
// Read items from the To Do list service.
//
// Add the access token to the authorization header of the request.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Call the To Do list service.
Console.WriteLine("Retrieving To Do list at {0}", DateTime.Now.ToString());
HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "/api/todolist");
if (response.IsSuccessStatusCode)
{
// Read the response and output it to the console.
string s = await response.Content.ReadAsStringAsync();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<TodoItem> toDoArray = serializer.Deserialize<List<TodoItem>>(s);
int count = 0;
foreach (TodoItem item in toDoArray)
{
Console.WriteLine(item.Title);
count++;
}
Console.WriteLine("Total item count: {0}\n", count);
}
else
{
Console.WriteLine("Failed to retrieve To Do list\nError: {0}\n", response.ReasonPhrase);
}
}
}
}
/*
The MIT License (MIT)
Copyright (c) 2018 Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using System.Configuration;
using System.IdentityModel.Tokens;
namespace TodoListService
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Changed
// app.UseWindowsAzureActiveDirectoryBearerAuthentication(
// new WindowsAzureActiveDirectoryBearerAuthenticationOptions
// {
// Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
// TokenValidationParameters = new TokenValidationParameters
// {
// ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
// }
// });
app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters()
{
SaveSigninToken = true,
ValidAudience = "https://localhost/ToDoListService"
// ValidAudience = "urn:microsoft:userinfo"
},
MetadataEndpoint = "https://my-adfs/FederationMetadata/2007-06/FederationMetadata.xml"
});
}
}
}
/*
The MIT License (MIT)
Copyright (c) 2018 Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
// The following using statements were added for this sample.
using System.Collections.Concurrent;
using System.Security.Claims;
using TodoListService.Models;
namespace TodoListService.Controllers
{
[Authorize]
public class TodoListController : ApiController
{
//
// To Do items list for all users. Since the list is stored in memory, it will go away if the service is cycled.
//
static ConcurrentBag<TodoItem> todoBag = new ConcurrentBag<TodoItem>();
// GET api/todolist
public IEnumerable<TodoItem> Get()
{
//
// The `role` claim tells you what permissions the client application has in the service.
// In this case we look for a `role` value of `access_as_application`
//
// Changed
//Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("roles");
//if (scopeClaim == null || (scopeClaim.Value != "access_as_application"))
//{
// throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The 'roles' claim does not contain 'access_as_application'or was not found" });
//}
// A user's To Do list is keyed off of the NameIdentifier claim, which contains an immutable, unique identifier for the user.
Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier);
return from todo in todoBag
//where todo.Owner == subject.Value
// Changed
where todo.Owner == "The owner"
select todo;
}
// POST api/todolist
public void Post(TodoItem todo)
{
Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("roles");
// Changed
//if (scopeClaim == null || (scopeClaim.Value != "access_as_application"))
//{
// throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The 'roles' claim does not contain 'access_as_application' or was not found" });
//}
if (null != todo && !string.IsNullOrWhiteSpace(todo.Title))
{
// Changed
//todoBag.Add(new TodoItem { Title = todo.Title, Owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value });
todoBag.Add(new TodoItem { Title = todo.Title, Owner = "The owner" });
}
}
}
}
...
<add key="ida:Audience" value="https://localhost/ToDoListService"/>
</appSettings>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment