-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomAuthStateProvider.cs
More file actions
60 lines (50 loc) · 2.02 KB
/
CustomAuthStateProvider.cs
File metadata and controls
60 lines (50 loc) · 2.02 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
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text.Json;
namespace BlazorAuth2
{
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private readonly ILocalStorageService _localStorage;
private readonly HttpClient _http;
public CustomAuthStateProvider(ILocalStorageService localStorage, HttpClient http)
{
_localStorage = localStorage;
_http = http;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
string token = await _localStorage.GetItemAsStringAsync("token");
var identity = new ClaimsIdentity();
_http.DefaultRequestHeaders.Authorization = null;
if (!string.IsNullOrEmpty(token))
{
identity = new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt");
_http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token.Replace("\"", ""));
}
var user = new ClaimsPrincipal(identity);
var state = new AuthenticationState(user);
NotifyAuthenticationStateChanged(Task.FromResult(state));
return state;
}
public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
var payload = jwt.Split('.')[1];
var jsonBytes = ParseBase64WithoutPadding(payload);
var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);
return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()));
}
private static byte[] ParseBase64WithoutPadding(string base64)
{
switch (base64.Length % 4)
{
case 2: base64 += "=="; break;
case 3: base64 += "="; break;
}
return Convert.FromBase64String(base64);
}
}
}