forked from MarimerLLC/csla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApplicationContextManagerBlazor.cs
277 lines (257 loc) · 8.79 KB
/
ApplicationContextManagerBlazor.cs
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#if NET5_0_OR_GREATER
//-----------------------------------------------------------------------
// <copyright file="ApplicationContextManager.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Application context manager that uses HttpContextAccessor</summary>
//-----------------------------------------------------------------------
using Csla.Core;
using Csla.State;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using System.Security.Principal;
namespace Csla.AspNetCore.Blazor
{
/// <summary>
/// Application context manager that adapts how to manage
/// per-user state and identity for server-rendered and
/// server-interactive Blazor modes.
/// </summary>
public class ApplicationContextManagerBlazor : IContextManager, IDisposable
{
/// <summary>
/// Creates an instance of the object, initializing it
/// with the required IServiceProvider.
/// </summary>
/// <param name="hca">IHttpContextAccessor service</param>
/// <param name="authenticationStateProvider">AuthenticationStateProvider service</param>
/// <param name="activeCircuitState"></param>
public ApplicationContextManagerBlazor(IHttpContextAccessor hca, AuthenticationStateProvider authenticationStateProvider, ActiveCircuitState activeCircuitState)
{
HttpContext = hca.HttpContext;
AuthenticationStateProvider = authenticationStateProvider;
ActiveCircuitState = activeCircuitState;
CurrentPrincipal = UnauthenticatedPrincipal;
AuthenticationStateProvider.AuthenticationStateChanged += AuthenticationStateProvider_AuthenticationStateChanged;
_ = InitializeUser();
}
private IPrincipal CurrentPrincipal { get; set; }
private readonly ClaimsPrincipal UnauthenticatedPrincipal = new();
private bool disposedValue;
/// <summary>
/// Gets the current HttpContext instance.
/// </summary>
protected AuthenticationStateProvider AuthenticationStateProvider { get; }
/// <summary>
/// Gets or sets a reference to the current ApplicationContext.
/// </summary>
public ApplicationContext ApplicationContext { get; set; }
/// <summary>
/// Gets the active circuit state.
/// </summary>
protected ActiveCircuitState ActiveCircuitState { get; }
/// <summary>
/// Gets or sets a reference to the current HttpContext.
/// </summary>
protected HttpContext HttpContext { get; set; }
private async Task InitializeUser()
{
if (ActiveCircuitState.CircuitExists)
{
Task<AuthenticationState> task;
try
{
task = AuthenticationStateProvider.GetAuthenticationStateAsync();
await task;
}
catch (InvalidOperationException ex)
{
task = Task.FromResult(new AuthenticationState(UnauthenticatedPrincipal));
string message = ex.Message;
//see ms error https://github.com/dotnet/aspnetcore/blob/87e324a61dcd15db4086b8a8ca7bd74ca1e0a513/src/Components/Server/src/Circuits/ServerAuthenticationStateProvider.cs#L16
//not much safe to test on except the error type and the use of this method name in message.
if (message.Contains(nameof(AuthenticationStateProvider.GetAuthenticationStateAsync)))
{
SetHostPrincipal(task);
}
else
{
throw;
}
}
AuthenticationStateProvider_AuthenticationStateChanged(task);
}
else if (HttpContext is not null)
{
CurrentPrincipal = HttpContext.User;
}
else
{
throw new InvalidOperationException("HttpContext==null, !CircuitExists");
}
}
private void AuthenticationStateProvider_AuthenticationStateChanged(Task<AuthenticationState> task)
{
if (task is null)
{
CurrentPrincipal = UnauthenticatedPrincipal;
}
else
{
task.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully && t.Result != null)
CurrentPrincipal = t.Result.User;
else
CurrentPrincipal = UnauthenticatedPrincipal;
});
}
}
/// <summary>
/// Gets a value indicating whether this
/// context manager is valid for use in
/// the current environment.
/// </summary>
public bool IsValid
{
get { return HttpContext is not null || ActiveCircuitState.CircuitExists; }
}
/// <summary>
/// Gets a value indicating whether the context manager
/// is stateful.
/// </summary>
public bool IsStatefulContext => true;
/// <summary>
/// Gets the current principal.
/// </summary>
public IPrincipal GetUser()
{
return CurrentPrincipal;
}
/// <summary>
/// Attempts to set the current principal on the registered
/// IHostEnvironmentAuthenticationStateProvider service.
/// </summary>
/// <param name="principal">Principal object.</param>
public virtual void SetUser(IPrincipal principal)
{
if (!ReferenceEquals(CurrentPrincipal, principal))
{
if (ActiveCircuitState.CircuitExists)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
SetHostPrincipal(Task.FromResult(new AuthenticationState(claimsPrincipal)));
}
else
{
throw new ArgumentException("typeof(principal) != ClaimsPrincipal");
}
}
else if (HttpContext is not null)
{
HttpContext.User = (ClaimsPrincipal)principal;
}
else
{
throw new InvalidOperationException("HttpContext==null, !CircuitExists");
}
CurrentPrincipal = principal;
}
}
private void SetHostPrincipal(Task<AuthenticationState> task)
{
if (AuthenticationStateProvider is IHostEnvironmentAuthenticationStateProvider hostProvider)
hostProvider.SetAuthenticationState(task);
}
/// <summary>
/// Gets the local context.
/// </summary>
public ContextDictionary GetLocalContext()
{
ContextDictionary localContext;
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session.TryGetValue("localContext", out var result);
if (result is ContextDictionary context)
{
localContext = context;
}
else
{
localContext = [];
SetLocalContext(localContext);
}
return localContext;
}
/// <summary>
/// Sets the local context.
/// </summary>
/// <param name="localContext">Local context.</param>
public void SetLocalContext(ContextDictionary localContext)
{
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session["localContext"] = localContext;
}
/// <summary>
/// Gets the client context.
/// </summary>
/// <param name="executionLocation"></param>
public ContextDictionary GetClientContext(ApplicationContext.ExecutionLocations executionLocation)
{
ContextDictionary clientContext;
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session.TryGetValue("clientContext", out var result);
if (result is ContextDictionary context)
{
clientContext = context;
}
else
{
clientContext = [];
SetClientContext(clientContext, ApplicationContext.ExecutionLocation);
}
return clientContext;
}
/// <summary>
/// Sets the client context.
/// </summary>
/// <param name="clientContext">Client context.</param>
/// <param name="executionLocation"></param>
public void SetClientContext(ContextDictionary clientContext, ApplicationContext.ExecutionLocations executionLocation)
{
var sessionManager = ApplicationContext.GetRequiredService<ISessionManager>();
var session = sessionManager.GetSession();
session["clientContext"] = clientContext;
}
/// <summary>
/// Dispose this object's resources.
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
AuthenticationStateProvider.AuthenticationStateChanged -= AuthenticationStateProvider_AuthenticationStateChanged;
}
disposedValue = true;
}
}
/// <summary>
/// Dispose this object's resources.
/// </summary>
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
#endif