Skip to content

asp net

Jean-Marc Prieur edited this page Nov 10, 2020 · 28 revisions

Support for ASP.NET classic

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
  • Constants
  • ClaimsPrincipalExtension which add extensions methods to a ClaimsPrincipal

Token cache serialization for MSAL.NET

This PR shows how an ASP.NET MVC application was modified to leverage the token cache serializers.

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.

 public static async Task<IConfidentialClientApplication> BuildConfidentialClientApplication()
 {
  IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(AuthenticationConfig.ClientId)
     .WithClientSecret(AuthenticationConfig.ClientSecret)
     .WithRedirectUri(AuthenticationConfig.RedirectUri)
     .WithAuthority(new Uri(AuthenticationConfig.Authority))
     .Build();

     // After the ConfidentialClientApplication is created, we overwrite its default UserTokenCache serialization with our implementation
     IMsalTokenCacheProvider memoryTokenCacheProvider = CreateTokenCacheSerializer();
     await memoryTokenCacheProvider.InitializeAsync(clientapp.UserTokenCache);
     return clientapp;
  }

with

 /// <summary>
 /// Implementation based on a Memory cache, But could be Redis, SQL, ...
 /// </summary>
 /// <returns></returns>
 private static IMemoryCache GetMemoryCache()
 {
   if (memoryCache == null)
   {
     IOptions<MemoryCacheOptions> options = Options.Create(new MemoryCacheOptions());
     memoryCache = new MemoryCache(options);
   }
   return memoryCache;
 }

 private static IMemoryCache memoryCache;

 private static IMsalTokenCacheProvider CreateTokenCacheSerializer()
 {
   IOptions<MsalMemoryTokenCacheOptions> msalCacheOptions = Options.Create(new MsalMemoryTokenCacheOptions());
   // You can override the options if you wish

   MsalMemoryTokenCacheProvider memoryTokenCacheProvider = new MsalMemoryTokenCacheProvider(GetMemoryCache(), msalCacheOptions);
   return memoryTokenCacheProvider;
 }

See Token cache serialization for details on the other token cache providers/serializers

Getting started with Microsoft Identity Web

Token cache serialization

Web apps

Web APIs

Daemon scenario

Advanced topics

FAQ

News

Contribute

Other resources

Clone this wiki locally