-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomAuthStateProvider.cs
More file actions
86 lines (74 loc) · 3.13 KB
/
CustomAuthStateProvider.cs
File metadata and controls
86 lines (74 loc) · 3.13 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
using ExampleAuthorizeView.Data;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace ExampleAuthorizeView
{
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private readonly ProtectedSessionStorage _sessionStorage;
private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
public CustomAuthStateProvider(ProtectedSessionStorage sessionStorage)
{
_sessionStorage = sessionStorage;
}
public async Task<Utenti?> GetUser()
{
var userSessionStorageResult = await _sessionStorage.GetAsync<Utenti>("user");
return userSessionStorageResult.Success ? userSessionStorageResult.Value : null;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
Utenti? userSession = await GetUser();
if (userSession == null)
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
else
{
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim("IdUser", userSession.IdUtente.ToString()),
new Claim("UserStatus", userSession.Stato),
new Claim(ClaimTypes.Name, userSession?.Nome ?? String.Empty),
new Claim(ClaimTypes.Email, userSession?.email ?? String.Empty),
new Claim(ClaimTypes.NameIdentifier, userSession.IdUtente.ToString())
}, "CustomAuth"));
return await Task.FromResult(new AuthenticationState(claimsPrincipal));
}
}
catch
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
}
public async Task UpdateAuthenticationState(Utenti parUser)
{
ClaimsPrincipal claimsPrincipal;
if (parUser != null)
{
await _sessionStorage.SetAsync("user", parUser);
claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim("IdUser", parUser.IdUtente.ToString()),
new Claim("UserStatus", parUser.Stato),
new Claim(ClaimTypes.Name, parUser.Nome),
new Claim(ClaimTypes.Email, parUser.email),
new Claim(ClaimTypes.NameIdentifier, parUser.IdUtente.ToString())
}));
}
else
{
await _sessionStorage.DeleteAsync("user");
claimsPrincipal = _anonymous;
}
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal)));
}
}
}