-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomAuthenticationStateProvider.cs
60 lines (51 loc) · 1.9 KB
/
CustomAuthenticationStateProvider.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
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
namespace demo {
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public CustomAuthenticationStateProvider()
{
this.CurrentUser = this.GetAnonymous();
}
private ClaimsPrincipal CurrentUser { get; set; }
private ClaimsPrincipal GetUser(string userName, string id, string role)
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes. Sid, id),
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.Role, role)
}, "Authentication type");
return new ClaimsPrincipal(identity);
}
private ClaimsPrincipal GetAnonymous()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Sid, "0"),
new Claim(ClaimTypes.Name, "Anonymous"),
new Claim(ClaimTypes.Role, "Anonymous")
}, null);
return new ClaimsPrincipal(identity);
}
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var task = Task.FromResult(new AuthenticationState(this.CurrentUser));
return task;
}
public Task<AuthenticationState> ChangeUser(string username, string id, string role)
{
this.CurrentUser = this.GetUser(username, id, role);
var task = this.GetAuthenticationStateAsync();
this.NotifyAuthenticationStateChanged(task);
return task;
}
public Task<AuthenticationState> Logout()
{
this.CurrentUser = this.GetAnonymous();
var task = this.GetAuthenticationStateAsync();
this.NotifyAuthenticationStateChanged(task);
return task;
}
}
}