This repository was archived by the owner on Jan 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathBffClientAuthenticationStateProvider.cs
77 lines (66 loc) · 2.93 KB
/
BffClientAuthenticationStateProvider.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
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.
using Duende.Bff.Blazor.Client.Internals;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Options;
namespace Duende.Bff.Blazor.Client;
public class BffClientAuthenticationStateProvider : AuthenticationStateProvider
{
public const string HttpClientName = "Duende.Bff.Blazor.Client:StateProvider";
private readonly IGetUserService _getUserService;
private readonly TimeProvider _timeProvider;
private readonly BffBlazorOptions _options;
private readonly ILogger<BffClientAuthenticationStateProvider> _logger;
/// <summary>
/// An <see cref="AuthenticationStateProvider"/> intended for use in Blazor
/// WASM. It polls the /bff/user endpoint to monitor session state.
/// </summary>
public BffClientAuthenticationStateProvider(
IGetUserService getUserService,
TimeProvider timeProvider,
IOptions<BffBlazorOptions> options,
ILogger<BffClientAuthenticationStateProvider> logger)
{
_getUserService = getUserService;
_timeProvider = timeProvider;
_options = options.Value;
_logger = logger;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
_getUserService.InitializeCache();
var user = await _getUserService.GetUserAsync();
var state = new AuthenticationState(user);
if (user.Identity is { IsAuthenticated: true })
{
_logger.LogInformation("starting background check..");
ITimer? timer = null;
async void TimerCallback(object? _)
{
var currentUser = await _getUserService.GetUserAsync(false);
// Always notify that auth state has changed, because the user
// management claims (usually) change over time.
//
// Future TODO - Someday we may want an extensibility point. If the
// user management claims have been customized, then auth state
// might not always change. In that case, we'd want to only fire
// if the user actually had changed.
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(currentUser)));
if (currentUser!.Identity!.IsAuthenticated == false)
{
_logger.LogInformation("user logged out");
if (timer != null)
{
await timer.DisposeAsync();
}
}
}
timer = _timeProvider.CreateTimer(TimerCallback,
null,
TimeSpan.FromMilliseconds(_options.StateProviderPollingDelay),
TimeSpan.FromMilliseconds(_options.StateProviderPollingInterval));
}
return state;
}
}