-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
48 additions
and
1 deletion.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
IssueVerifiableEmployee/RejectSessionCookieWhenAccountNotInCacheEvents.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
using Microsoft.AspNetCore.Authentication.Cookies; | ||
using Microsoft.Identity.Client; | ||
using Microsoft.Identity.Web; | ||
|
||
namespace BffMicrosoftEntraID.Server; | ||
|
||
public class RejectSessionCookieWhenAccountNotInCacheEvents : CookieAuthenticationEvents | ||
{ | ||
private readonly string[] _downstreamScopes; | ||
|
||
public RejectSessionCookieWhenAccountNotInCacheEvents(string[] downstreamScopes) | ||
{ | ||
_downstreamScopes = downstreamScopes; | ||
} | ||
|
||
public async override Task ValidatePrincipal(CookieValidatePrincipalContext context) | ||
{ | ||
try | ||
{ | ||
var tokenAcquisition = context.HttpContext.RequestServices | ||
.GetRequiredService<ITokenAcquisition>(); | ||
|
||
string token = await tokenAcquisition.GetAccessTokenForUserAsync(scopes: _downstreamScopes, | ||
user: context.Principal); | ||
} | ||
catch (MicrosoftIdentityWebChallengeUserException ex) when (AccountDoesNotExitInTokenCache(ex)) | ||
{ | ||
context.RejectPrincipal(); | ||
} | ||
} | ||
|
||
private static bool AccountDoesNotExitInTokenCache(MicrosoftIdentityWebChallengeUserException ex) | ||
{ | ||
return ex.InnerException is MsalUiRequiredException | ||
&& (ex.InnerException as MsalUiRequiredException)!.ErrorCode == "user_null"; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters