-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathBlazorAuthenticationChallengeHandler.cs
More file actions
124 lines (103 loc) · 4.25 KB
/
BlazorAuthenticationChallengeHandler.cs
File metadata and controls
124 lines (103 loc) · 4.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// NOTE: This file is included in Microsoft.Identity.Web package (v3.3.0+).
// This copy is maintained for AI skill reference and documentation purposes.
// For production use, reference the NuGet package directly.
using System.Security.Claims;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
namespace Microsoft.Identity.Web;
/// <summary>
/// Handles authentication challenges for Blazor Server components.
/// Provides functionality for incremental consent and Conditional Access scenarios.
/// </summary>
public class BlazorAuthenticationChallengeHandler(
NavigationManager navigation,
AuthenticationStateProvider authenticationStateProvider,
IConfiguration configuration)
{
private const string MsaTenantId = "9188040d-6c67-4c5b-b112-36a304b66dad";
/// <summary>
/// Gets the current user's authentication state.
/// </summary>
public async Task<ClaimsPrincipal> GetUserAsync()
{
var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
return authState.User;
}
/// <summary>
/// Checks if the current user is authenticated.
/// </summary>
public async Task<bool> IsAuthenticatedAsync()
{
var user = await GetUserAsync();
return user.Identity?.IsAuthenticated == true;
}
/// <summary>
/// Handles exceptions that may require user re-authentication.
/// Returns true if a challenge was initiated, false otherwise.
/// </summary>
public async Task<bool> HandleExceptionAsync(Exception exception)
{
var challengeException = exception as MicrosoftIdentityWebChallengeUserException
?? exception.InnerException as MicrosoftIdentityWebChallengeUserException;
if (challengeException != null)
{
var user = await GetUserAsync();
ChallengeUser(user, challengeException.Scopes, challengeException.MsalUiRequiredException?.Claims);
return true;
}
return false;
}
/// <summary>
/// Initiates a challenge to authenticate the user or request additional consent.
/// </summary>
public void ChallengeUser(ClaimsPrincipal user, string[]? scopes = null, string? claims = null)
{
var currentUri = navigation.Uri;
// Build scopes string (add OIDC scopes)
var allScopes = (scopes ?? [])
.Union(["openid", "offline_access", "profile"])
.Distinct();
var scopeString = Uri.EscapeDataString(string.Join(" ", allScopes));
// Get login hint from user claims
var loginHint = Uri.EscapeDataString(GetLoginHint(user));
// Get domain hint
var domainHint = Uri.EscapeDataString(GetDomainHint(user));
// Build the challenge URL
var challengeUrl = $"/authentication/login?returnUrl={Uri.EscapeDataString(currentUri)}" +
$"&scope={scopeString}" +
$"&loginHint={loginHint}" +
$"&domainHint={domainHint}";
// Add claims if present (for Conditional Access)
if (!string.IsNullOrEmpty(claims))
{
challengeUrl += $"&claims={Uri.EscapeDataString(claims)}";
}
navigation.NavigateTo(challengeUrl, forceLoad: true);
}
/// <summary>
/// Initiates a challenge with scopes from configuration.
/// </summary>
public async Task ChallengeUserWithConfiguredScopesAsync(string configurationSection)
{
var user = await GetUserAsync();
var scopes = configuration.GetSection(configurationSection).Get<string[]>();
ChallengeUser(user, scopes);
}
private static string GetLoginHint(ClaimsPrincipal user)
{
return user.FindFirst("preferred_username")?.Value ??
user.FindFirst("login_hint")?.Value ??
string.Empty;
}
private static string GetDomainHint(ClaimsPrincipal user)
{
var tenantId = user.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value ??
user.FindFirst("tid")?.Value;
if (string.IsNullOrEmpty(tenantId))
return "organizations";
// MSA tenant
if (tenantId == MsaTenantId)
return "consumers";
return "organizations";
}
}