Skip to content

Commit 5340ec6

Browse files
author
Kalyan Krishna
committed
Fixed bugs with guest account
1 parent 70bcb8a commit 5340ec6

File tree

8 files changed

+48
-43
lines changed

8 files changed

+48
-43
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,8 @@
8585
/4-WebApp-your-API/4-1-Your-API/Client/bin/Debug/netcoreapp2.2
8686
/4-WebApp-your-API/4-1-Your-API/Client/obj
8787
/4-WebApp-your-API/4-1-Your-API/.vs/WebApp-OpenIDConnect-DotNet
88+
/4-WebApp-your-API/Client/bin/Debug/netcoreapp2.2
89+
/4-WebApp-your-API/Client/obj
90+
/4-WebApp-your-API/packages
91+
/4-WebApp-your-API/TodoListService/bin/Debug/netcoreapp2.2
92+
/4-WebApp-your-API/TodoListService/obj

4-WebApp-your-API/AppCreationScripts/Cleanup.ps1

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ param(
55
[string] $tenantId
66
)
77

8-
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
8+
if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) {
99
Install-Module "AzureAD" -Scope CurrentUser
1010
}
1111
Import-Module AzureAD
@@ -44,7 +44,7 @@ This function removes the Azure AD applications for the sample. These applicatio
4444
$tenantId = $creds.Tenant.Id
4545
}
4646
$tenant = Get-AzureADTenantDetail
47-
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
47+
$tenantName = ($tenant.VerifiedDomains | Where-Object { $_._Default -eq $True }).Name
4848

4949
# Removes the applications
5050
Write-Host "Cleaning-up applications from tenant '$tenantName'"
@@ -56,19 +56,31 @@ This function removes the Azure AD applications for the sample. These applicatio
5656
{
5757
Remove-AzureADApplication -ObjectId $apps.ObjectId
5858
}
59-
# Get-AzureRmADServicePrincipal -SearchString "TodoListService-aspnetcore-webapi" | ForEach-Object {Remove-AzureRmADServicePrincipal -ObjectId $_.Id -Confirm:$false}
60-
Write-Host "Removed TodoListService-aspnetcore-webapi."
6159

60+
foreach ($app in $apps)
61+
{
62+
Remove-AzureADApplication -ObjectId $app.ObjectId
63+
Write-Host "Removed TodoListService-aspnetcore-webapi.."
64+
}
65+
# also remove service principals of this app
66+
Get-AzureADServicePrincipal -filter "DisplayName eq 'TodoListService-aspnetcore-webapi'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false}
67+
6268
Write-Host "Removing 'client' (TodoListClient-aspnetcore-webapi) if needed"
6369
Get-AzureADApplication -Filter "DisplayName eq 'TodoListClient-aspnetcore-webapi'" | ForEach-Object {Remove-AzureADApplication -ObjectId $_.ObjectId }
6470
$apps = Get-AzureADApplication -Filter "DisplayName eq 'TodoListClient-aspnetcore-webapi'"
6571
if ($apps)
6672
{
6773
Remove-AzureADApplication -ObjectId $apps.ObjectId
6874
}
69-
# Get-AzureRmADServicePrincipal -SearchString "TodoListClient-aspnetcore-webapi" | ForEach-Object {Remove-AzureRmADServicePrincipal -ObjectId $_.Id -Confirm:$false}
70-
Write-Host "Removed TodoListClient-aspnetcore-webapi."
7175

76+
foreach ($app in $apps)
77+
{
78+
Remove-AzureADApplication -ObjectId $app.ObjectId
79+
Write-Host "Removed TodoListClient-aspnetcore-webapi.."
80+
}
81+
# also remove service principals of this app
82+
Get-AzureADServicePrincipal -filter "DisplayName eq 'TodoListClient-aspnetcore-webapi'" | ForEach-Object {Remove-AzureADServicePrincipal -ObjectId $_.Id -Confirm:$false}
83+
7284
}
7385

74-
Cleanup -Credential $Credential -tenantId $TenantId
86+
Cleanup -Credential $Credential -tenantId $TenantId

4-WebApp-your-API/Client/TodoListClient.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
<ItemGroup>
2525
<PackageReference Include="Microsoft.AspNetCore.App" />
2626
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="2.2.0" />
27-
<PackageReference Include="Microsoft.Graph" Version="1.12.0" />
27+
<PackageReference Include="Microsoft.Graph" Version="1.16.0" />
2828
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
2929
<PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
3030
</ItemGroup>

4-WebApp-your-API/TodoListService/Controllers/TodoListController.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2525
using Microsoft.AspNetCore.Authorization;
2626
using Microsoft.AspNetCore.Http;
2727
using Microsoft.AspNetCore.Mvc;
28+
using Microsoft.Identity.Web.Client;
2829
using System.Collections.Concurrent;
2930
using System.Collections.Generic;
3031
using System.Linq;

Microsoft.Identity.Web/Client/MsalUiRequiredExceptionFilterAttribute.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ private bool CanBeSolvedByReSignInUser(MsalUiRequiredException ex)
6161
/// Build Authentication properties needed for an incremental consent.
6262
/// </summary>
6363
/// <param name="scopes">Scopes to request</param>
64-
/// <param name="ex">ui is present</param>
64+
/// <param name="ex">MsalUiRequiredException instance</param>
6565
/// <param name="context">current http context in the pipeline</param>
6666
/// <returns>AuthenticationProperties</returns>
6767
private AuthenticationProperties BuildAuthenticationPropertiesForIncrementalConsent(

Microsoft.Identity.Web/Client/TokenAcquisition.cs

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public TokenAcquisition(IConfiguration configuration, IMSALAppTokenCacheProvider
9898
/// From the configuration of the Authentication of the ASP.NET Core Web API:
9999
/// <code>OpenIdConnectOptions options;</code>
100100
///
101-
/// Subscribe to the authorization code recieved event:
101+
/// Subscribe to the authorization code received event:
102102
/// <code>
103103
/// options.Events = new OpenIdConnectEvents();
104104
/// options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
@@ -128,6 +128,13 @@ public async Task AddAccountToCacheFromAuthorizationCode(AuthorizationCodeReceiv
128128
// even if it's not done yet, so that it does not concurrently call the Token endpoint.
129129
context.HandleCodeRedemption();
130130

131+
// The cache will need the claims from the ID token. In the case of guest scenarios
132+
// If they are not yet in the HttpContext.User's claims, adding them.
133+
if (!context.HttpContext.User.Claims.Any())
134+
{
135+
(context.HttpContext.User.Identity as ClaimsIdentity).AddClaims(context.Principal.Claims);
136+
}
137+
131138
var application = BuildConfidentialClientApplication(context.HttpContext, context.Principal);
132139

133140
// Do not share the access token with ASP.NET Core otherwise ASP.NET will cache it and will not send the OAuth 2.0 request in
@@ -351,32 +358,19 @@ private async Task<string> GetAccessTokenOnBehalfOfUser(IConfidentialClientAppli
351358

352359
AuthenticationResult result = null;
353360

354-
try
361+
if (string.IsNullOrWhiteSpace(tenant))
355362
{
356-
if (string.IsNullOrWhiteSpace(tenant))
357-
{
358-
result = await application.AcquireTokenSilent(scopes.Except(scopesRequestedByMsalNet), account)
359-
.ExecuteAsync();
360-
}
361-
else
362-
{
363-
string authority = application.Authority.Replace(new Uri(application.Authority).PathAndQuery, $"/{tenant}/");
364-
result = await application.AcquireTokenSilent(scopes.Except(scopesRequestedByMsalNet), account)
365-
.WithAuthority(authority)
366-
.ExecuteAsync();
367-
}
363+
result = await application.AcquireTokenSilent(scopes.Except(scopesRequestedByMsalNet), account)
364+
.ExecuteAsync();
368365
}
369-
catch (MsalUiRequiredException ex)
366+
else
370367
{
371-
// A MsalUiRequiredException happened on AcquireTokenSilent.
372-
// This indicates you need to call AcquireTokenInteractive to acquire a token
373-
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
374-
375-
result = await application.AcquireTokenForClient(scopes)
376-
.ExecuteAsync();
368+
string authority = application.Authority.Replace(new Uri(application.Authority).PathAndQuery, $"/{tenant}/");
369+
result = await application.AcquireTokenSilent(scopes.Except(scopesRequestedByMsalNet), account)
370+
.WithAuthority(authority)
371+
.ExecuteAsync();
377372
}
378373

379-
380374
return result.AccessToken;
381375
}
382376

Microsoft.Identity.Web/Client/TokenCacheProviders/InMemory/MSALPerUserMemoryTokenCacheProvider.cs

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,7 @@ private void UserTokenCacheAfterAccessNotification(TokenCacheNotificationArgs ar
9494
// if the access operation resulted in a cache update
9595
if (args.HasStateChanged)
9696
{
97-
string cacheKey = args.Account?.HomeAccountId?.Identifier;
98-
if (string.IsNullOrEmpty(cacheKey))
99-
{
100-
cacheKey = httpContextAccessor.HttpContext.User.GetMsalAccountId();
101-
}
97+
string cacheKey = httpContextAccessor.HttpContext.User.GetMsalAccountId();
10298

10399
if (string.IsNullOrWhiteSpace(cacheKey))
104100
return;
@@ -116,17 +112,14 @@ private void UserTokenCacheAfterAccessNotification(TokenCacheNotificationArgs ar
116112
/// <param name="args">Contains parameters used by the MSAL call accessing the cache.</param>
117113
private void UserTokenCacheBeforeAccessNotification(TokenCacheNotificationArgs args)
118114
{
119-
string cacheKey = args.Account?.HomeAccountId?.Identifier;
120-
if (string.IsNullOrEmpty(cacheKey))
121-
{
122-
cacheKey = httpContextAccessor.HttpContext.User.GetMsalAccountId();
123-
}
115+
116+
string cacheKey = httpContextAccessor.HttpContext.User.GetMsalAccountId();
124117

125118
if (string.IsNullOrWhiteSpace(cacheKey))
126119
return;
127120

128121
byte[] tokenCacheBytes = (byte[])this.memoryCache.Get(cacheKey);
129-
args.TokenCache.DeserializeMsalV3(tokenCacheBytes, shouldClearExistingCache:true);
122+
args.TokenCache.DeserializeMsalV3(tokenCacheBytes, shouldClearExistingCache: true);
130123
}
131124

132125
/// <summary>

Microsoft.Identity.Web/Microsoft.Identity.Web.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
<ItemGroup>
88
<PackageReference Include="Microsoft.AspNetCore.App" />
99
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="2.2.0" />
10-
<PackageReference Include="Microsoft.Identity.Client" Version="4.0.0" />
10+
<PackageReference Include="Microsoft.Identity.Client" Version="4.1.0" />
1111
</ItemGroup>
1212
</Project>

0 commit comments

Comments
 (0)