-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmyServerAuthenticationStateProvider.cs
More file actions
85 lines (76 loc) · 3.03 KB
/
myServerAuthenticationStateProvider.cs
File metadata and controls
85 lines (76 loc) · 3.03 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
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.Extensions.Configuration;
using System;
using System.Net.Sockets;
using System.Security.Claims;
using System.Threading.Tasks;
namespace AspNetCoreAuthMultiLang
{
public class MyServerAuthenticationStateProvider : AuthenticationStateProvider
{
public readonly NavigationManager navigationManager;
public readonly ProtectedSessionStorage protectedSessionStore;
public MyServerAuthenticationStateProvider(
NavigationManager NavigationManager,
ProtectedSessionStorage ProtectedSessionStore
)
{
navigationManager = NavigationManager;
protectedSessionStore = ProtectedSessionStore;
}
public string m_login = null;
public string m_culture = "fr-FR";
public bool IsAuthenticated()
{
return m_login!=null;
}
public async Task TryLoginAsync()
{
if (!IsAuthenticated())
{
var result = await protectedSessionStore.GetAsync<string>("login");
if (result.Success)
await DoLoginAsync(result.Value, null);
}
}
public void ApplyCulture(string culture, string redirectionUri) // fr-FR for example
{
var query = $"?culture={System.Net.WebUtility.UrlEncode(culture)}&" + $"redirectionUri={System.Net.WebUtility.UrlEncode(redirectionUri)}";
navigationManager.NavigateTo("/api/v1/auth/setCulture" + query, forceLoad: true);
}
public async Task DoLoginAsync(string login, string path)
{
m_login = login;
await protectedSessionStore.SetAsync("login", login);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
if (!string.IsNullOrEmpty(path))
ApplyCulture(m_culture, path);
}
public async Task DoLogoutAsync()
{
m_login=null;
await protectedSessionStore.DeleteAsync("login").ConfigureAwait(false);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
AuthenticationState result;
if (IsAuthenticated())
{
result = new AuthenticationState(
new ClaimsPrincipal(
new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, m_login),
new Claim(ClaimTypes.Role, "demo_role"),
new Claim(ClaimTypes.Role, "Admin"),
}, "PutAppNameHere"
)));
}
else
result = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); // Not authenticated
return Task.FromResult(result);
}
}
}