-
Notifications
You must be signed in to change notification settings - Fork 219
asp net
Jean-Marc Prieur edited this page Jun 23, 2021
·
28 revisions
Microsoft.Identity.Web is mostly aimed at ASP.NET Core. However, some of its classes are also available for ASP.NET. These are:
- Token cache serializers and adapters for MSAL.NET
- Helper methods to load certificates
- Constants. See Contants.cs
- ClaimsPrincipalExtension which add extensions methods to a ClaimsPrincipal. See Utility classes
The principle is the same, except that ASP.NET will probably not use dependency injection. You'd probably instantiate the classes yourself in your code.
#using Microsoft.Identity.Web
private static IConfidentialClientApplication clientapp;
public static async Task<IConfidentialClientApplication> BuildConfidentialClientApplication()
{
if (clientapp == null)
{
clientapp = ConfidentialClientApplicationBuilder.Create(AuthenticationConfig.ClientId)
.WithClientSecret(AuthenticationConfig.ClientSecret)
.WithRedirectUri(AuthenticationConfig.RedirectUri)
.WithAuthority(new Uri(AuthenticationConfig.Authority))
.Build();
// Create the confidential client application
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(clientId)
// Alternatively to the certificate you can use .WithClientSecret(clientSecret)
.WithCertificate(certDescription.Certificate)
.WithTenantId(tenant)
.Build();
// Add an in-memory token cache
app.UseInMemoryTokenCaches();
// Or
// In memory distributed token cache
app.UseDistributedTokenCaches(services =>
{
// In net462/net472, requires to reference Microsoft.Extensions.Caching.Memory
services.AddDistributedMemoryCache();
});
// Or
// SQL Server token cache
app.UseDistributedTokenCaches(services =>
{
services.AddDistributedSqlServerCache(options =>
{
// In net462/net472, requires to reference Microsoft.Extensions.Caching.Memory
// Requires to reference Microsoft.Extensions.Caching.SqlServer
options.ConnectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestCache;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
options.SchemaName = "dbo";
options.TableName = "TestCache";
// You don't want the SQL token cache to be purged before the access token has expired. Usually
// access tokens expire after 1 hour (but this can be changed by token lifetime policies), whereas
// the default sliding expiration for the distributed SQL database is 20 mins.
// Use a value which is above 60 mins (or the lifetime of a token in case of longer lived tokens)
options.DefaultSlidingExpiration = TimeSpan.FromMinutes(90);
});
});
// Or
// Redis token cache
app.UseDistributedTokenCaches(services =>
{
// Requires to reference Microsoft.Extensions.Caching.StackExchangeRedis
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "Redis";
});
});
// Or
// Cosmos DB token cache
app.UseDistributedTokenCaches(services =>
{
// Requires to reference Microsoft.Extensions.Caching.Cosmos (preview)
services.AddCosmosCache((CosmosCacheOptions cacheOptions) =>
{
cacheOptions.ContainerName = Configuration["CosmosCacheContainer"];
cacheOptions.DatabaseName = Configuration["CosmosCacheDatabase"];
cacheOptions.ClientBuilder = new CosmosClientBuilder(Configuration["CosmosConnectionString"]);
cacheOptions.CreateIfNotExists = true;
});
});
return clientapp;
}
See Token cache serialization for details on the other token cache providers/serializers
- Using this cache in a .NET Framework and .NET Core (not ASP.NET) application is showed-cased in this sample ConfidentialClientTokenCache
- The following sample is an ASP.NET web app using the same technics: https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect (See WebApp/Utils/MsalAppBuilder.cs
Microsoft.Identity.Web 1.6.0 and later expose the DefaultCertificateLoader
class to .NET framework.
// Certificate
string keyVaultContainer = "https://WebAppsApisTests.vault.azure.net";
string keyVaultReference = "MsIdWebScenarioTestCert";
CertificateDescription certDescription = CertificateDescription.FromKeyVault(keyVaultContainer, keyVaultReference);
ICertificateLoader certificateLoader = new DefaultCertificateLoader();
certificateLoader.LoadIfNeeded(certDescription);
// Create the confidential client application
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithCertificate(certDescription.Certificate)
.WithTenantId(tenant)
.Build();
For details, see:
- the Using certicates article for details.
- the ConfidentialClientTokenCache which showcases loading a certificate from KeyVault.
Sample | Platform | Description |
---|---|---|
active-directory-dotnet-v1-to-v2 | Desktop (Console) | Visual Studio solution illustrating the migration of Azure AD v1.0 applications (using ADAL.NET) to Azure AD v2.0 applications, also named converged applications (using MSAL.NET), in particular ConfidentialClientTokenCache |
ms-identity-aspnet-webapp-openidconnect | ASP.NET (net472) | Example of token cache serialization in an ASP.NET MVC application (using MSAL.NET). See in particular MsalAppBuilder |
active-directory-dotnetcore-daemon-v2 | .NET Core (Console) | Part of the daemon tutorial, this chapter shows how to have a daemon using certificates acquired from KeyVault. |
- Home
- Why use Microsoft Identity Web?
- Web apps
- Web APIs
- Using certificates
- Minimal support for .NET FW Classic
- Logging
- Azure AD B2C limitations
- Samples
- Web apps
- Web app samples
- Web app template
- Call an API from a web app
- Managing incremental consent and conditional access
- Web app troubleshooting
- Deploy to App Services Linux containers or with proxies
- SameSite cookies
- Hybrid SPA
- Web APIs
- Web API samples
- Web API template
- Call an API from a web API
- Token Decryption
- Web API troubleshooting
- web API protected by ACLs instead of app roles
- gRPC apps
- Azure Functions
- Long running processes in web APIs
- Authorization policies
- Generic API
- Customization
- Logging
- Calling graph with specific scopes/tenant
- Multiple Authentication Schemes
- Utility classes
- Setting FIC+MSI
- Mixing web app and web API
- Deploying to Azure App Services
- Azure AD B2C issuer claim support
- Performance
- specify Microsoft Graph scopes and app-permissions
- Integrate with Azure App Services authentication
- Ajax calls and incremental consent and conditional access
- Back channel proxys
- Client capabilities