Files

83 lines
2.5 KiB
C#
Raw Permalink Normal View History

2024-01-19 17:25:56 +01:00
using Microsoft.AspNetCore.Components.Authorization;
using SecureBank.Common;
using SecureBank.Website.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
2024-01-23 15:41:59 +01:00
using System.IdentityModel.Tokens.Jwt;
2024-01-19 17:25:56 +01:00
using System.Text;
using System.Threading.Tasks;
namespace SecureBank.Website.Authentication
{
public class TokenAuthenticationStateProvider : AuthenticationStateProvider
{
#region SERVICES
private readonly IAccountsService _accountsService;
private readonly AuthenticationHelper _authenticationHelper;
private readonly HttpClient _httpClient;
#endregion
#region CONSTRUCTORS
2024-01-23 15:41:59 +01:00
public TokenAuthenticationStateProvider(IAccountsService accountsService, AuthenticationHelper authenticationHelper, HttpClient httpClient)
{
2024-01-19 17:25:56 +01:00
_accountsService = accountsService;
_authenticationHelper = authenticationHelper;
_httpClient = httpClient;
}
#endregion
#region PUBLIC METHODS
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
_httpClient.DefaultRequestHeaders.Authorization = null;
AuthenticationState state = new AuthenticationState(new ClaimsPrincipal());
string token = await _authenticationHelper.GetToken();
if (string.IsNullOrWhiteSpace(token))
{
return state;
}
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
APIResponse<string> refreshResponse = await _accountsService.AuthenticationRefresh();
2024-01-23 15:41:59 +01:00
if (refreshResponse.Status != ResponseStatus.Ok)
2024-01-19 17:25:56 +01:00
{
2024-01-23 15:41:59 +01:00
await _authenticationHelper.RemoveToken();
2024-01-19 17:25:56 +01:00
_httpClient.DefaultRequestHeaders.Authorization = null;
return state;
}
token = refreshResponse.Data;
2024-01-23 15:41:59 +01:00
await _authenticationHelper.SaveToken(token);
2024-01-19 17:25:56 +01:00
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
2024-01-23 15:41:59 +01:00
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken tokenParsed = tokenHandler.ReadJwtToken(token);
state = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(tokenParsed.Claims)));
2024-01-19 17:25:56 +01:00
return state;
}
#endregion
}
}