| | 1 | | using Microsoft.JSInterop; |
| | 2 | | using System.Security.Claims; |
| | 3 | | using System.IdentityModel.Tokens.Jwt; |
| | 4 | | using Microsoft.AspNetCore.Components.Authorization; |
| | 5 | |
|
| | 6 | | namespace Syki.Front.Auth; |
| | 7 | |
|
| 396 | 8 | | public class SykiAuthStateProvider(ILocalStorageService storage) : AuthenticationStateProvider |
| | 9 | | { |
| | 10 | | public override async Task<AuthenticationState> GetAuthenticationStateAsync() |
| | 11 | | { |
| 383 | 12 | | var jwt = await storage.GetItemAsync("AccessToken"); |
| | 13 | |
|
| 383 | 14 | | if (jwt.IsEmpty()) |
| | 15 | | { |
| 0 | 16 | | return new(new ClaimsPrincipal(new ClaimsIdentity())); |
| | 17 | | } |
| | 18 | |
|
| 383 | 19 | | return new(CreateClaimsPrincipalFromToken(jwt!)); |
| 383 | 20 | | } |
| | 21 | |
|
| | 22 | | public void MarkUserAsAuthenticated() |
| | 23 | | { |
| 383 | 24 | | NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); |
| 383 | 25 | | } |
| | 26 | |
|
| | 27 | | public void MarkUserAsLoggedOut() |
| | 28 | | { |
| 0 | 29 | | NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); |
| 0 | 30 | | } |
| | 31 | |
|
| | 32 | | private static ClaimsPrincipal CreateClaimsPrincipalFromToken(string token) |
| | 33 | | { |
| 383 | 34 | | var tokenHandler = new JwtSecurityTokenHandler(); |
| | 35 | |
|
| 383 | 36 | | var identity = new ClaimsIdentity(); |
| | 37 | |
|
| 383 | 38 | | if (tokenHandler.CanReadToken(token)) |
| | 39 | | { |
| 383 | 40 | | var jwtSecurityToken = tokenHandler.ReadJwtToken(token); |
| 383 | 41 | | identity = new(jwtSecurityToken.Claims, "Bearer"); |
| | 42 | |
|
| 383 | 43 | | identity.AddClaim(new Claim(ClaimTypes.Role, identity.FindFirst("role")!.Value)); |
| | 44 | | } |
| | 45 | |
|
| 383 | 46 | | return new(identity); |
| | 47 | | } |
| | 48 | | } |