-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAuth0AuthenticationStateProvider.cs
52 lines (42 loc) · 1.54 KB
/
Auth0AuthenticationStateProvider.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
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;
using Auth0.OidcClient;
public class Auth0AuthenticationStateProvider : AuthenticationStateProvider
{
private ClaimsPrincipal currentUser = new ClaimsPrincipal(new ClaimsIdentity());
private readonly Auth0Client auth0Client;
public Auth0AuthenticationStateProvider(Auth0Client client) {
auth0Client = client;
}
public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
Task.FromResult(new AuthenticationState(currentUser));
public Task LogInAsync()
{
var loginTask = LogInAsyncCore();
NotifyAuthenticationStateChanged(loginTask);
return loginTask;
async Task<AuthenticationState> LogInAsyncCore()
{
var user = await LoginWithAuth0Async();
currentUser = user;
return new AuthenticationState(currentUser);
}
}
private async Task<ClaimsPrincipal> LoginWithAuth0Async()
{
var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity());
var loginResult = await auth0Client.LoginAsync();
if (!loginResult.IsError) {
authenticatedUser = loginResult.User;
}
return authenticatedUser;
}
public async void LogOut()
{
await auth0Client.LogoutAsync();
currentUser = new ClaimsPrincipal(new ClaimsIdentity());
NotifyAuthenticationStateChanged(
Task.FromResult(new AuthenticationState(currentUser)));
}
}