File size: 2,131 Bytes
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01be06d
 
 
 
72f2be7
01be06d
 
 
 
 
 
72f2be7
01be06d
3418204
 
72f2be7
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
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;

namespace TaskTrackingSystem.WebApp.Components;

// Cookie auth with in-circuit cache so interactive Blazor pages keep the signed-in user.
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserSessionState _sessionState;
    private static readonly AuthenticationState Anonymous =
        new(new ClaimsPrincipal(new ClaimsIdentity()));

    public CustomAuthenticationStateProvider(IHttpContextAccessor httpContextAccessor, UserSessionState sessionState)
    {
        _httpContextAccessor = httpContextAccessor;
        _sessionState = sessionState;
    }

    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var user = _httpContextAccessor.HttpContext?.User;
        if (user?.Identity?.IsAuthenticated == true)
        {
            CacheUser(user);
            return Task.FromResult(new AuthenticationState(user));
        }

        if (_sessionState.CachedUser?.Identity?.IsAuthenticated == true)
        {
            return Task.FromResult(new AuthenticationState(_sessionState.CachedUser));
        }

        return Task.FromResult(Anonymous);
    }

    public void NotifyUserAuthenticationChanged()
    {
        NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
    }

    private void CacheUser(ClaimsPrincipal user)
    {
        _sessionState.CachedUser = user;

        var token = user.FindFirst("jwt_token")?.Value;
        if (!string.IsNullOrEmpty(token))
        {
            _sessionState.Token = token;
        }

        var roleId = user.FindFirst("role_id")?.Value;
        if (!string.IsNullOrWhiteSpace(roleId))
        {
            _sessionState.CachedAccessRoleId = $"id:{roleId}";
            return;
        }

        var roleName = user.FindFirst(System.Security.Claims.ClaimTypes.Role)?.Value;
        if (!string.IsNullOrWhiteSpace(roleName))
        {
            _sessionState.CachedAccessRoleId = $"name:{roleName}";
        }
    }
}