Skip to content

Commit

Permalink
make tokenAcqusition a singleton (#174)
Browse files Browse the repository at this point in the history
* make tokenAcqusition a singleton

* fixing a couple of static analysis errors

Co-authored-by: Jean-Marc Prieur <jmprieur@microsoft.com>
  • Loading branch information
jennyf19 and jmprieur authored May 26, 2020
1 parent dcea25e commit 3e30d12
Show file tree
Hide file tree
Showing 9 changed files with 40 additions and 14 deletions.
6 changes: 6 additions & 0 deletions src/Microsoft.Identity.Web/MicrosoftIdentityOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ public class MicrosoftIdentityOptions : OpenIdConnectOptions
/// </summary>
public string PostLogoutRedirectUri { get; set; }

/// <summary>
/// Gets or sets TokenAcquisition as a Singleton. There are scenarios, like using the Graph SDK,
/// which require TokenAcquisition to be a Singleton.
/// </summary>
public bool SingletonTokenAcquisition { get; set; } = false;

/// <summary>
/// Gets or sets the edit profile user flow name for B2C, e.g. b2c_1_edit_profile.
/// </summary>
Expand Down
10 changes: 5 additions & 5 deletions src/Microsoft.Identity.Web/Resource/RegisterValidAudience.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void RegisterAudienceValidation(
/// the default App ID URI generated by the portal is api://{clientID}
/// - However, the audience (aud) of the token acquired to access this Web API is different depending
/// on the "accepted access token version" for the Web API:
/// - if accepted token version is 1.0, the audience provided in the token
/// - if accepted token version is 1.0, the audience provided in the token
/// by the Microsoft identity platform (formerly Azure AD v2.0) endpoint is: api://{ClientID}
/// - if the accepted token version is 2.0, the audience provided by Azure AD v2.0 in the token
/// is {CliendID}
Expand All @@ -52,10 +52,10 @@ public void RegisterAudienceValidation(
/// considers that this is the default App ID URI as explained abovce. When developer provide the
/// "Audience" member, its available in the TokenValidationParameter.ValidAudience.
/// </summary>
/// <param name="audiences">audiences in the security token</param>
/// <param name="securityToken">Security token from which to validate the audiences</param>
/// <param name="validationParameters">Token validation parameters</param>
/// <returns>true is the token is valid, and false, otherwise</returns>
/// <param name="audiences">audiences in the security token.</param>
/// <param name="securityToken">Security token from which to validate the audiences.</param>
/// <param name="validationParameters">Token validation parameters.</param>
/// <returns>true is the token is valid, and false, otherwise.</returns>
internal /*for test only*/ bool ValidateAudience(
IEnumerable<string> audiences,
SecurityToken securityToken,
Expand Down
15 changes: 13 additions & 2 deletions src/Microsoft.Identity.Web/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public static class ServiceCollectionExtensions
/// Add the token acquisition service.
/// </summary>
/// <param name="services">Service collection.</param>
/// <param name="isTokenAcquisitionSingleton"></param>
/// <returns>the service collection.</returns>
/// <example>
/// This method is typically called from the Startup.ConfigureServices(IServiceCollection services)
Expand All @@ -28,11 +29,21 @@ public static class ServiceCollectionExtensions
/// ;
/// </code>
/// </example>
public static IServiceCollection AddTokenAcquisition(this IServiceCollection services)
public static IServiceCollection AddTokenAcquisition(
this IServiceCollection services,
bool isTokenAcquisitionSingleton = false)
{
// Token acquisition service
services.AddHttpContextAccessor();
services.AddScoped<ITokenAcquisition, TokenAcquisition>();
if (!isTokenAcquisitionSingleton)
{
services.AddScoped<ITokenAcquisition, TokenAcquisition>();
}
else
{
services.AddSingleton<ITokenAcquisition, TokenAcquisition>();
}

return services;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,15 @@ public static IServiceCollection AddProtectedWebApiCallsProtectedWebApi(
Action<MicrosoftIdentityOptions> configureMicrosoftIdentityOptions,
string jwtBearerScheme = JwtBearerDefaults.AuthenticationScheme)
{
services.AddTokenAcquisition();
services.AddHttpContextAccessor();
services.Configure<ConfidentialClientApplicationOptions>(configureConfidentialClientApplicationOptions);
services.Configure<MicrosoftIdentityOptions>(configureMicrosoftIdentityOptions);

var microsoftIdentityOptions = new MicrosoftIdentityOptions();
configureMicrosoftIdentityOptions(microsoftIdentityOptions);

services.AddTokenAcquisition(microsoftIdentityOptions.SingletonTokenAcquisition);
services.AddHttpContextAccessor();

services.Configure<JwtBearerOptions>(jwtBearerScheme, options =>
{
options.Events ??= new JwtBearerEvents();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@ public static IServiceCollection AddWebAppCallsProtectedWebApi(
services.Configure<ConfidentialClientApplicationOptions>(configureConfidentialClientApplicationOptions);

services.AddHttpContextAccessor();
services.AddTokenAcquisition();

var microsoftIdentityOptions = new MicrosoftIdentityOptions();
configureMicrosoftIdentityOptions(microsoftIdentityOptions);

services.AddTokenAcquisition(microsoftIdentityOptions.SingletonTokenAcquisition);

services.Configure<OpenIdConnectOptions>(openIdConnectScheme, options =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public MsalTestTokenCacheProvider(
: base(microsoftIdentityOptions, httpContextAccessor)
{
MemoryCache = memoryCache;
_cacheOptions = cacheOptions.Value;
_cacheOptions = cacheOptions?.Value;
}

public IMemoryCache MemoryCache { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private void InitializeTokenAcquisitionObjects()
logger);
}

private IHttpContextAccessor CreateMockHttpContextAccessor()
private static IHttpContextAccessor CreateMockHttpContextAccessor()
{
var mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
mockHttpContextAccessor.HttpContext = new DefaultHttpContext();
Expand All @@ -184,6 +184,7 @@ private IHttpContextAccessor CreateMockHttpContextAccessor()
private void BuildTheRequiredServices()
{
var services = new ServiceCollection();

services.AddTokenAcquisition();
services.AddTransient(
_provider => Options.Create(new MicrosoftIdentityOptions
Expand Down
2 changes: 1 addition & 1 deletion tests/Microsoft.Identity.Web.Test/WebApiExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ public async Task AddProtectedWebApiCallsProtectedWebApi_WithConfigName()
provider.GetRequiredService<IOptionsFactory<ConfidentialClientApplicationOptions>>().Create(string.Empty);
provider.GetRequiredService<IOptionsFactory<MicrosoftIdentityOptions>>().Create(string.Empty);

config.Received(2).GetSection(_configSectionName);
config.Received(3).GetSection(_configSectionName);

await AddProtectedWebApiCallsProtectedWebApi_TestCommon(services, provider, tokenValidatedFuncMock).ConfigureAwait(false);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/Microsoft.Identity.Web.Test/WebAppExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ public async Task AddWebAppCallsProtectedWebApi_WithConfigNameParameters()
provider.GetRequiredService<IOptionsFactory<ConfidentialClientApplicationOptions>>().Create(string.Empty);
provider.GetRequiredService<IOptionsFactory<MicrosoftIdentityOptions>>().Create(string.Empty);

configMock.Received(2).GetSection(_configSectionName);
configMock.Received(3).GetSection(_configSectionName);

var oidcOptions = provider.GetRequiredService<IOptionsFactory<OpenIdConnectOptions>>().Create(_oidcScheme);

Expand Down

0 comments on commit 3e30d12

Please sign in to comment.