page_type: sample languages:
This code sample uses the Conditional Access Auth Context to demand a higher bar of authentication for certain high-privileged and sensitive operations in a protected Web API.
To use the CA Auth context in a Web app, please try theUse the Conditional Access auth context to perform step-up authentication for high-privilege operations in a Web app code sample.
:information_source: Check out the recorded session on this topic: Use Conditional Access Auth Context in your app for step-up authentication
Prerequisites
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-ca-auth-context.git
or download and extract the repository .zip file.
:warning: To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
dotnet restore
dotnet restore
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
As a first step you'll need to:
TodoListService-acrs-webapi
.https://localhost:44351/
.
Note that there are more than one redirect URIs used in this sample. You'll need to add them from the Authentication tab later after the app has been created successfully.
https://localhost:44351/signin-oidc
app secret
),Note: The Graph permission, **Policy.ReadWrite.ConditionalAccess** is required for creating new auth context records by this sample. In production, the permission, **Policy.Read.ConditionalAccess** should be sufficient to read existing values and thus is recommended.
Set
next to the Application ID URI to generate a URI that is unique for this app.api://{clientId}
) by selecting Save.access_as_user
.Access TodoListService-acrs-webapi
.Allows the app to access TodoListService-acrs-webapi as the signed-in user.
Access TodoListService-acrs-webapi
.Allow the application to access TodoListService-acrs-webapi on your behalf.
acrs
and client capabilities claim xms_cc
claim."optionalClaims":
{
"accessToken": [
{
"additionalProperties": [],
"essential": false,
"name": "xms_cc",
"source": null
}
],
"idToken": [],
"saml2Token": []
}
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
TodoListService\appsettings.json
file.Domain
and replace the existing value with your Azure AD tenant name.TenantId
and replace the existing value with your Azure AD tenant ID.ClientId
and replace the existing value with the application ID (clientId) of TodoListService-acrs-webapi
app copied from the Azure portal.ClientSecret
and replace the existing value with the key you saved during the creation of TodoListService-acrs-webapi
copied from the Azure portal.TodoListClient-acrs-webapp
.https://localhost:44321/
.
Note that there are more than one redirect URIs used in this sample. You'll need to add them from the Authentication tab later after the app has been created successfully.
https://localhost:44321/signin-oidc
https://localhost:44321/signout-oidc
.app secret
),TodoListService-acrs-webapi
.Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
TodoListClient\appsettings.json
file.Domain
and replace the existing value with your Azure AD tenant name.TenantId
and replace the existing value with your Azure AD tenant ID.ClientId
and replace the existing value with the application ID (clientId) of TodoListClient-acrs-webapp
app copied from the Azure portal.ClientSecret
and replace the existing value with the key you saved during the creation of TodoListClient-acrs-webapp
copied from the Azure portal.TodoListScope
and replace the existing value with Scope.TodoListBaseAddress
and replace the existing value with the base address of TodoListService-acrs-webapi
(by default https://localhost:44351
).For Visual Studio Users
Clean the solution, rebuild the solution, and run it. You might want to go into the solution properties and set both projects as startup projects, with the service project starting first.
cd TodoListClient
dotnet restore
dotnet run
cd TodoListService
dotnet restore
dotnet run
We'd first replicate the experience of an admin configuring the auth contexts. For that, browse to https://localhost:44321
and sign-in using a tenant Admin account. Click on the Admin link on the menu.
As a first step, you will ensure that a set of Auth Context is already available in this tenant. Click the CreateOrFetch button to check if they exist. If they don't , the code will create three sample auth context entries for you. These three entires are named Require strong authentication
, Require compliant devices
and Require trusted locations
.
Note: The Graph permission, Policy.ReadWrite.ConditionalAccess is required for creating new records. In production, the permission, Policy.Read.ConditionalAccess should be sufficient to read existing values and thus is recommended.
Select an operation in the Web API and an Authentication Context
value to apply and select SaveOrUpdate. This updates this mapping in the local app's database. We advise you use the same auth context value for operations if possible, as this ensures that the suer is redirected to Azure AD just once to perform the step-up authN.
Note: When changing auth context mappings, have the user sign-out and sign-back in for the changes to take effect.
Go to `View Details page to get details of data saved on the Web API side in its database. You can select Delete if you need to delete a mapping from the local database.
The web API is now ready to challenge users for step-up auth for the selected operations.
Select New policy and go to Cloud apps or actions. In dropdown select Authentication context. The newly created auth context values will be listed for you to be used in this CA policy.
Select the value and create the policy as required. For example, you might want the user to satisfy a MFA challenge if the auth context value is 'Medium'.
https://localhost:44321
and sign-in.Select TodoList
page and perform the operations.
If an operation was saved for a certain authContext and there is a CA policy configured and enabled, the user will be redirected to Azure AD and ask to perform the required step(s) like MFA.
:information_source: Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
In Startup.cs
, below lines of code enables Microsoft identity platform endpoint to protect the Web API.
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
Below lines of code enables Microsoft identity platform endpoint to authenticate the users and to call MS Graph.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration, "AzureAd", subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("GraphBeta"))
.AddInMemoryTokenCaches();
In AdminController.cs
, the method GetAuthenticationContextValues returns a default set of AuthN context values for the app to work with, either from Graph or a default hard coded set.
private async Task<Dictionary<string, string>> GetAuthenticationContextValues()
{
Dictionary<string, string> dictACRValues = new Dictionary<string, string>()
{
{"C1","Require strong authentication" },
{"C2","Require compliant devices" },
{"C3","Require trusted locations" }
};
string sessionKey = "ACRS";
if (HttpContext.Session.Get<Dictionary<string, string>>(sessionKey) != default)
{
dictACRValues = HttpContext.Session.Get<Dictionary<string, string>>(sessionKey);
}
else
{
var existingAuthContexts = await _authContextClassReferencesOperations.ListAuthenticationContextClassReferencesAsync();
if (existingAuthContexts.Count() > 0)
{
dictACRValues.Clear();
foreach (var authContext in existingAuthContexts)
{
dictACRValues.Add(authContext.Id, authContext.DisplayName);
}
HttpContext.Session.Set<Dictionary<string, string>>(sessionKey, dictACRValues);
}
}
return dictACRValues;
}
CreateOrFetch method checks if auth context exists then retrieve the list from graph by calling ListAuthenticationContextClassReferencesAsync method else call CreateAuthContextViaGraph to create the auth context.
public async Task<List<Beta.AuthenticationContextClassReference>> CreateOrFetch()
{
var lstPolicies = await _authContextClassReferencesOperations.ListAuthenticationContextClassReferencesAsync();
if (lstPolicies?.Count > 0)
{
return lstPolicies;
}
else
{
await CreateAuthContextViaGraph();
}
return lstPolicies;
}
AuthenticationContextClassReferencesOperations.cs
contains methods that call graph to perform various operations. In current sample we have used create and get methods. CreateAuthenticationContextClassReferenceAsync method creates the auth context: Note: this class calls the /beta endpoint of Graph as the API was available only on the /beta endpoint at the time of this sample's publishing
public async Task<Beta.AuthenticationContextClassReference> CreateAuthenticationContextClassReferenceAsync(string id, string displayName, string description, bool IsAvailable)
{
Beta.AuthenticationContextClassReference newACRObject = null;
try
{
newACRObject = await _graphServiceClient.Identity.ConditionalAccess.AuthenticationContextClassReferences.Request().AddAsync(new Beta.AuthenticationContextClassReference
{
Id = id,
DisplayName = displayName,
Description = description,
IsAvailable = IsAvailable,
ODataType = null
});
}
catch (ServiceException e)
{
Console.WriteLine("We could not add a new ACR: " + e.Error.Message);
return null;
}
return newACRObject;
}
ListAuthenticationContextClassReferencesAsync method get the existing auth context values from graph.
public async Task<List<Beta.AuthenticationContextClassReference>> ListAuthenticationContextClassReferencesAsync()
{
List<Beta.AuthenticationContextClassReference> allAuthenticationContextClassReferences = new List<Beta.AuthenticationContextClassReference>();
try
{
Beta.IConditionalAccessRootAuthenticationContextClassReferencesCollectionPage authenticationContextClassreferences = await _graphServiceClient.Identity.ConditionalAccess.AuthenticationContextClassReferences.Request().GetAsync();
if (authenticationContextClassreferences != null)
{
allAuthenticationContextClassReferences = await ProcessIAuthenticationContextClassReferenceRootPoliciesCollectionPage(authenticationContextClassreferences);
}
}
catch (ServiceException e)
{
Console.WriteLine($"We could not retrieve the existing ACRs: {e}");
if (e.InnerException != null)
{
var exp = (MicrosoftIdentityWebChallengeUserException)e.InnerException;
throw exp;
}
throw e;
}
return allAuthenticationContextClassReferences;
}
In TodoListController.cs
, the method CheckForRequiredAuthContext retrieves the acrsValue from database for the request method. Then checks if the access token has acrs
claim with acrsValue. If does not exists then adds WWW-Authenticate and throws UnauthorizedAccessException exception.
public void CheckForRequiredAuthContext(string method)
{
string authType = _commonDBContext.AuthContext.FirstOrDefault(x => x.Operation == method && x.TenantId == _configuration["AzureAD:TenantId"])?.AuthContextId;
if (!string.IsNullOrEmpty(authType))
{
HttpContext context = this.HttpContext;
string authenticationContextClassReferencesClaim = "acrs";
if (context == null || context.User == null || context.User.Claims == null || !context.User.Claims.Any())
{
throw new ArgumentNullException("No Usercontext is available to pick claims from");
}
Claim acrsClaim = context.User.FindAll(authenticationContextClassReferencesClaim).FirstOrDefault(x => x.Value == authType);
if (acrsClaim == null || acrsClaim.Value != authType)
{
string clientId = _configuration.GetSection("AzureAd").GetSection("ClientId").Value;
var base64str = Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"access_token\":{\"acrs\":{\"essential\":true,\"value\":\"" + authType + "\"}}}"));
context.Response.Headers.Append("WWW-Authenticate", $"Bearer realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", client_id=\"" + clientId + "\", error=\"insufficient_claims\", claims=\"" + base64str + "\", cc_type=\"authcontext\"");
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
string message = string.Format(CultureInfo.InvariantCulture, "The presented access tokens had insufficient claims. Please request for claims requested in the WWW-Authentication header and try again.");
context.Response.WriteAsync(message);
context.Response.CompleteAsync();
throw new UnauthorizedAccessException(message);
}
}
}
/// <summary>
/// Evaluates for the presence of the client capabilities claim (xms_cc) and accordingly returns a response if present.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public bool IsClientCapableofClaimsChallenge(HttpContext context)
{
string clientCapabilitiesClaim = "xms_cc";
if (context == null || context.User == null || context.User.Claims == null || !context.User.Claims.Any())
{
throw new ArgumentNullException("No Usercontext is available to pick claims from");
}
Claim ccClaim = context.User.FindAll(clientCapabilitiesClaim).FirstOrDefault(x => x.Type == "xms_cc");
if (ccClaim != null && ccClaim.Value == "cp1")
{
return true;
}
return false;
}
Methods in TodoListController.cs
challenges the user if exception is thrown from Web API, as shown in below method:
public async Task<ActionResult> Create([Bind("Title,Owner")] Todo todo)
{
try
{
await _todoListService.AddAsync(todo);
}
catch (WebApiMsalUiRequiredException hex)
{
try
{
var claimChallenge = ExtractAuthenticationHeader.ExtractHeaderValues(hex);
_consentHandler.ChallengeUser(new string[] { "user.read" }, claimChallenge);
return new EmptyResult();
}
catch (Exception ex)
{
_consentHandler.HandleException(ex);
}
Console.WriteLine(hex.Message);
}
return RedirectToAction("Index");
}
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory
azure-ad-b2c
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.