Skip to content

Commit

Permalink
fix for anonymous controller (#1425)
Browse files Browse the repository at this point in the history
  • Loading branch information
jennyf19 authored Sep 3, 2021
1 parent 6be9af7 commit 51af003
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Microsoft.Identity.Web/TokenAcquisition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,13 @@ public Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
authenticationScheme = GetEffectiveAuthenticationScheme(authenticationScheme);
MergedOptions mergedOptions = GetOptions(authenticationScheme);

// Case of an anonymous controller, no [Authorize] attribute will trigger the merge options
if (string.IsNullOrEmpty(mergedOptions.Instance))
{
var mergedOptionsMonitor = _serviceProvider.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>();
mergedOptionsMonitor.Get(JwtBearerDefaults.AuthenticationScheme);
}

if (string.IsNullOrEmpty(tenant))
{
tenant = mergedOptions.TenantId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -214,6 +217,33 @@ async Task authResult() =>
Assert.Equal(0, _msalTestTokenCacheProvider.Count);
}

[Fact]
public async Task GetAccessTokenForApp_WithAnonymousController_Async()
{
var serviceCollection = new ServiceCollection();
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "AzureAd:Instance", "https://login.microsoftonline.com/" },
{ "AzureAd:TenantId", TestConstants.ConfidentialClientLabTenant },
{ "AzureAd:ClientId", TestConstants.ConfidentialClientId },
{ "AzureAd:ClientSecret", _ccaSecret },
})
.Build();
serviceCollection.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();

var services = serviceCollection.BuildServiceProvider();

var tokenAcquisition = services.GetRequiredService<ITokenAcquisition>();

var token = await tokenAcquisition.GetAccessTokenForAppAsync("https://graph.microsoft.com/.default").ConfigureAwait(false);

Assert.NotNull(token);
}

private void InitializeTokenAcquisitionObjects()
{
MergedOptions mergedOptions = _provider.GetRequiredService<IOptionsMonitor<MergedOptions>>().Get(OpenIdConnectDefaults.AuthenticationScheme);
Expand Down

0 comments on commit 51af003

Please sign in to comment.