-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
AuthorizeRouteViewTest.cs
471 lines (413 loc) · 21.8 KB
/
AuthorizeRouteViewTest.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Binding;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Test.Helpers;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Components.Authorization;
public class AuthorizeRouteViewTest
{
private static readonly IReadOnlyDictionary<string, object> EmptyParametersDictionary = new Dictionary<string, object>();
private readonly TestAuthenticationStateProvider _authenticationStateProvider;
private readonly TestRenderer _renderer;
private readonly RouteView _authorizeRouteViewComponent;
private readonly int _authorizeRouteViewComponentId;
private readonly TestAuthorizationService _testAuthorizationService;
public AuthorizeRouteViewTest()
{
_authenticationStateProvider = new TestAuthenticationStateProvider();
_authenticationStateProvider.CurrentAuthStateTask = Task.FromResult(
new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
_testAuthorizationService = new TestAuthorizationService();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<AuthenticationStateProvider>(_authenticationStateProvider);
serviceCollection.AddSingleton<IAuthorizationPolicyProvider, TestAuthorizationPolicyProvider>();
serviceCollection.AddSingleton<IAuthorizationService>(_testAuthorizationService);
serviceCollection.AddSingleton<NavigationManager, TestNavigationManager>();
var services = serviceCollection.BuildServiceProvider();
_renderer = new TestRenderer(services);
var componentFactory = new ComponentFactory(new DefaultComponentActivator());
_authorizeRouteViewComponent = (AuthorizeRouteView)componentFactory.InstantiateComponent(services, typeof(AuthorizeRouteView));
_authorizeRouteViewComponentId = _renderer.AssignRootComponentId(_authorizeRouteViewComponent);
}
[Fact]
public void WhenAuthorized_RendersPageInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), new Dictionary<string, object>
{
{ nameof(TestPageRequiringAuthorization.Message), "Hello, world!" }
});
_testAuthorizationService.NextResult = AuthorizationResult.Success();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Assert: renders layout
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<CascadingModelBinder>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
edit => AssertPrependText(batch, edit, "Layout ends here"));
var cascadingModelBinderDiff = batch.GetComponentDiffs<CascadingModelBinder>().Single();
Assert.Collection(cascadingModelBinderDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<CascadingValue<ModelBindingContext>>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
});
var cascadingValueDiff = batch.GetComponentDiffs<CascadingValue<ModelBindingContext>>().Single();
Assert.Collection(cascadingValueDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<TestPageRequiringAuthorization>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
});
// Assert: renders page
var pageDiff = batch.GetComponentDiffs<TestPageRequiringAuthorization>().Single();
Assert.Collection(pageDiff.Edits,
edit => AssertPrependText(batch, edit, "Hello from the page with message: Hello, world!"));
}
[Fact]
public void AuthorizesWhenResourceIsSet()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), new Dictionary<string, object>
{
{ nameof(TestPageRequiringAuthorization.Message), "Hello, world!" }
});
var resource = "foo";
_testAuthorizationService.NextResult = AuthorizationResult.Success();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.Resource), resource }
}));
// Assert: renders layout
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<CascadingModelBinder>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
edit => AssertPrependText(batch, edit, "Layout ends here"));
var cascadingModelBinderDiff = batch.GetComponentDiffs<CascadingModelBinder>().Single();
Assert.Collection(cascadingModelBinderDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<CascadingValue<ModelBindingContext>>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
});
var cascadingValueDiff = batch.GetComponentDiffs<CascadingValue<ModelBindingContext>>().Single();
Assert.Collection(cascadingValueDiff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<TestPageRequiringAuthorization>(batch.ReferenceFrames[edit.ReferenceFrameIndex]);
});
// Assert: renders page
var pageDiff = batch.GetComponentDiffs<TestPageRequiringAuthorization>().Single();
Assert.Collection(pageDiff.Edits,
edit => AssertPrependText(batch, edit, "Hello from the page with message: Hello, world!"));
// Assert: Asserts that the Resource is present and set to "foo"
Assert.Collection(_testAuthorizationService.AuthorizeCalls, call =>
{
Assert.Equal(resource, call.resource.ToString());
});
}
[Fact]
public void NotAuthorizedWhenResourceMissing()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
_testAuthorizationService.NextResult = AuthorizationResult.Failed();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Assert: renders layout containing "not authorized" message
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Not authorized"),
edit => AssertPrependText(batch, edit, "Layout ends here"));
// Assert: Asserts that the Resource is Null
Assert.Collection(_testAuthorizationService.AuthorizeCalls, call =>
{
Assert.Null(call.resource);
});
}
[Fact]
public void WhenNotAuthorized_RendersDefaultNotAuthorizedContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
_testAuthorizationService.NextResult = AuthorizationResult.Failed();
// Act
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Assert: renders layout containing "not authorized" message
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Not authorized"),
edit => AssertPrependText(batch, edit, "Layout ends here"));
}
[Fact]
public void WhenNotAuthorized_RendersCustomNotAuthorizedContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
_testAuthorizationService.NextResult = AuthorizationResult.Failed();
_authenticationStateProvider.CurrentAuthStateTask = Task.FromResult(new AuthenticationState(
new ClaimsPrincipal(new TestIdentity { Name = "Bert" })));
// Act
RenderFragment<AuthenticationState> customNotAuthorized =
state => builder => builder.AddContent(0, $"Go away, {state.User.Identity.Name}");
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.NotAuthorized), customNotAuthorized },
}));
// Assert: renders layout containing "not authorized" message
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Go away, Bert"),
edit => AssertPrependText(batch, edit, "Layout ends here"));
}
[Fact]
public async Task WhenAuthorizing_RendersDefaultAuthorizingContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
var authStateTcs = new TaskCompletionSource<AuthenticationState>();
_authenticationStateProvider.CurrentAuthStateTask = authStateTcs.Task;
RenderFragment<AuthenticationState> customNotAuthorized =
state => builder => builder.AddContent(0, $"Go away, {state.User.Identity.Name}");
// Act
var firstRenderTask = _renderer.RenderRootComponentAsync(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.NotAuthorized), customNotAuthorized },
}));
// Assert: renders layout containing "authorizing" message
Assert.False(firstRenderTask.IsCompleted);
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Authorizing..."),
edit => AssertPrependText(batch, edit, "Layout ends here"));
// Act 2: updates when authorization completes
authStateTcs.SetResult(new AuthenticationState(
new ClaimsPrincipal(new TestIdentity { Name = "Bert" })));
await firstRenderTask;
// Assert 2: Only the layout is updated
batch = _renderer.Batches.Skip(1).Single();
var nonEmptyDiff = batch.DiffsInOrder.Where(d => d.Edits.Any()).Single();
Assert.Equal(layoutDiff.ComponentId, nonEmptyDiff.ComponentId);
Assert.Collection(nonEmptyDiff.Edits, edit =>
{
Assert.Equal(RenderTreeEditType.UpdateText, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
AssertFrame.Text(batch.ReferenceFrames[edit.ReferenceFrameIndex], "Go away, Bert");
});
}
[Fact]
public void WhenAuthorizing_RendersCustomAuthorizingContentInsideLayout()
{
// Arrange
var routeData = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
var authStateTcs = new TaskCompletionSource<AuthenticationState>();
_authenticationStateProvider.CurrentAuthStateTask = authStateTcs.Task;
RenderFragment customAuthorizing =
builder => builder.AddContent(0, "Hold on, we're checking your papers.");
// Act
var firstRenderTask = _renderer.RenderRootComponentAsync(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
{ nameof(AuthorizeRouteView.Authorizing), customAuthorizing },
}));
// Assert: renders layout containing "authorizing" message
Assert.False(firstRenderTask.IsCompleted);
var batch = _renderer.Batches.Single();
var layoutDiff = batch.GetComponentDiffs<TestLayout>().Single();
Assert.Collection(layoutDiff.Edits,
edit => AssertPrependText(batch, edit, "Layout starts here"),
edit => AssertPrependText(batch, edit, "Hold on, we're checking your papers."),
edit => AssertPrependText(batch, edit, "Layout ends here"));
}
[Fact]
public void WithoutCascadedAuthenticationState_WrapsOutputInCascadingAuthenticationState()
{
// Arrange/Act
var routeData = new RouteData(typeof(TestPageWithNoAuthorization), EmptyParametersDictionary);
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData }
}));
// Assert
var batch = _renderer.Batches.Single();
var componentInstances = batch.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Component)
.Select(f => f.Component);
Assert.Collection(componentInstances,
// This is the hierarchy inside the AuthorizeRouteView, which contains its
// own CascadingAuthenticationState
component => Assert.IsType<CascadingAuthenticationState>(component),
component => Assert.IsType<CascadingValue<Task<AuthenticationState>>>(component),
component => Assert.IsAssignableFrom<AuthorizeViewCore>(component),
component => Assert.IsType<LayoutView>(component),
component => Assert.IsType<CascadingModelBinder>(component),
component => Assert.IsType<CascadingValue<ModelBindingContext>>(component),
component => Assert.IsType<TestPageWithNoAuthorization>(component));
}
[Fact]
public void WithCascadedAuthenticationState_DoesNotWrapOutputInCascadingAuthenticationState()
{
// Arrange
var routeData = new RouteData(typeof(TestPageWithNoAuthorization), EmptyParametersDictionary);
var rootComponent = new AuthorizeRouteViewWithExistingCascadedAuthenticationState(
_authenticationStateProvider.CurrentAuthStateTask,
routeData);
var rootComponentId = _renderer.AssignRootComponentId(rootComponent);
// Act
_renderer.RenderRootComponent(rootComponentId);
// Assert
var batch = _renderer.Batches.Single();
var componentInstances = batch.ReferenceFrames
.Where(f => f.FrameType == RenderTreeFrameType.Component)
.Select(f => f.Component);
Assert.Collection(componentInstances,
// This is the externally-supplied cascading value
component => Assert.IsType<CascadingValue<Task<AuthenticationState>>>(component),
component => Assert.IsType<AuthorizeRouteView>(component),
// This is the hierarchy inside the AuthorizeRouteView. It doesn't contain a
// further CascadingAuthenticationState
component => Assert.IsAssignableFrom<AuthorizeViewCore>(component),
component => Assert.IsType<LayoutView>(component),
component => Assert.IsType<CascadingModelBinder>(component),
component => Assert.IsType<CascadingValue<ModelBindingContext>>(component),
component => Assert.IsType<TestPageWithNoAuthorization>(component));
}
[Fact]
public void UpdatesOutputWhenRouteDataChanges()
{
// Arrange/Act 1: Start on some route
// Not asserting about the initial output, as that is covered by other tests
var routeData = new RouteData(typeof(TestPageWithNoAuthorization), EmptyParametersDictionary);
_renderer.RenderRootComponent(_authorizeRouteViewComponentId, ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData },
{ nameof(AuthorizeRouteView.DefaultLayout), typeof(TestLayout) },
}));
// Act 2: Move to another route
var routeData2 = new RouteData(typeof(TestPageRequiringAuthorization), EmptyParametersDictionary);
var render2Task = _renderer.Dispatcher.InvokeAsync(() => _authorizeRouteViewComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(AuthorizeRouteView.RouteData), routeData2 },
})));
// Assert: we retain the layout instance, and mutate its contents
Assert.True(render2Task.IsCompletedSuccessfully);
Assert.Equal(2, _renderer.Batches.Count);
var batch2 = _renderer.Batches[1];
var diff = batch2.DiffsInOrder.Where(d => d.Edits.Any()).Single();
Assert.Collection(diff.Edits,
edit =>
{
// Inside the layout, we add the new content
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
AssertFrame.Text(batch2.ReferenceFrames[edit.ReferenceFrameIndex], "Not authorized");
},
edit =>
{
// ... and remove the old content
Assert.Equal(RenderTreeEditType.RemoveFrame, edit.Type);
Assert.Equal(2, edit.SiblingIndex);
});
}
private static void AssertPrependText(CapturedBatch batch, RenderTreeEdit edit, string text)
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
ref var referenceFrame = ref batch.ReferenceFrames[edit.ReferenceFrameIndex];
AssertFrame.Text(referenceFrame, text);
}
class TestPageWithNoAuthorization : ComponentBase { }
[Authorize]
class TestPageRequiringAuthorization : ComponentBase
{
[Parameter] public string Message { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, $"Hello from the page with message: {Message}");
}
}
class TestLayout : LayoutComponentBase
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, "Layout starts here");
builder.AddContent(1, Body);
builder.AddContent(2, "Layout ends here");
}
}
class AuthorizeRouteViewWithExistingCascadedAuthenticationState : AutoRenderComponent
{
private readonly Task<AuthenticationState> _authenticationState;
private readonly RouteData _routeData;
public AuthorizeRouteViewWithExistingCascadedAuthenticationState(
Task<AuthenticationState> authenticationState,
RouteData routeData)
{
_authenticationState = authenticationState;
_routeData = routeData;
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenComponent<CascadingValue<Task<AuthenticationState>>>(0);
builder.AddComponentParameter(1, nameof(CascadingValue<object>.Value), _authenticationState);
builder.AddComponentParameter(2, nameof(CascadingValue<object>.ChildContent), (RenderFragment)(builder =>
{
builder.OpenComponent<AuthorizeRouteView>(0);
builder.AddComponentParameter(1, nameof(AuthorizeRouteView.RouteData), _routeData);
builder.CloseComponent();
}));
builder.CloseComponent();
}
}
class TestNavigationManager : NavigationManager
{
public TestNavigationManager()
{
Initialize("https://localhost:85/subdir/", "https://localhost:85/subdir/path?query=value#hash");
}
}
}