我在使用Blazor身份验证时遇到了问题。我已经实现了
例如,我有一个Profile.razor页面组件,其包含
我怀疑
TokenAuthenticationStateProvider.cs ——
AuthenticationStateProvider
, 一切都运行正常,但是在登入或登出之后,我需要手动刷新页面以更新AuthenticationState
。例如,我有一个Profile.razor页面组件,其包含
@attribute [Authorize]
。我无法在登录后打开此页面,就像我没有得到授权一样,但在页面重新加载后一切都很好。退出也是同样的情况。我怀疑
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync())
没有起作用,但我无法理解问题所在。TokenAuthenticationStateProvider.cs ——
AuthenticationStateProvider
的实现。public class TokenAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly TokenStorage tokenStorage;
public TokenAuthenticationStateProvider(TokenStorage tokenStorage)
{
this.tokenStorage = tokenStorage;
}
public void StateChanged()
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); // <- Does nothing
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var token = await tokenStorage.GetAccessToken();
var identity = string.IsNullOrEmpty(token)
? new ClaimsIdentity()
: new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt");
return new AuthenticationState(new ClaimsPrincipal(identity));
}
private 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);
}
}
TokenStorage.cs - 访问和刷新令牌存储
public class TokenStorage
{
private readonly ILocalStorage localStorage;
public TokenStorage(
ILocalStorage localStorage)
{
this.localStorage = localStorage;
}
public async Task SetTokensAsync(string accessToken, string refreshToken)
{
await localStorage.SetItem("accessToken", accessToken);
await localStorage.SetItem("refreshToken", refreshToken);
}
public async Task<string> GetAccessToken()
{
return await localStorage.GetItem<string>("accessToken");
}
public async Task<string> GetRefreshToken()
{
return await localStorage.GetItem<string>("refreshToken");
}
public async Task RemoveTokens()
{
await localStorage.RemoveItem("accessToken");
await localStorage.RemoveItem("refreshToken");
}
}
AccountService.cs - 这是一个具有登录和注销功能的服务。我调用 authState.StateChanged()
来更新 AuthenticationState
public class AccountService
{
private readonly TokenStorage tokenStorage;
private readonly HttpClient httpClient;
private readonly TokenAuthenticationStateProvider authState;
private readonly string authApiUrl = "/api/authentication";
public AccountService(
TokenStorage tokenStorage,
HttpClient httpClient,
TokenAuthenticationStateProvider authState)
{
this.tokenStorage = tokenStorage;
this.httpClient = httpClient;
this.authState = authState;
}
public async Task Login(LoginCredentialsDto credentials)
{
var response = await httpClient.PostJsonAsync<AuthenticationResponseDto>($"{authApiUrl}/login", credentials);
await tokenStorage.SetTokensAsync(response.AccessToken, response.RefreshToken);
authState.StateChanged();
}
public async Task Logout()
{
var refreshToken = await tokenStorage.GetRefreshToken();
await httpClient.GetJsonAsync<AuthenticationResponseDto>($"{authApiUrl}/logout/{refreshToken}");
await tokenStorage.RemoveTokens();
authState.StateChanged();
}
}
App.razor
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" Context="routeData">
<Found>
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<h1>Not authorized!</h1>
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Profile.razor
@page "/profile/{UserName}"
@attribute [Authorize]
<h1>Profile</h1>
@code {
...
}
Startup.cs - 客户端启动
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddValidatorsFromAssemblyContaining<LoginCredentialsDtoValidator>();
services.AddStorage();
services.AddScoped<TokenStorage>();
services.AddScoped<AccountService>();
services.AddScoped<TokenAuthenticationStateProvider>();
services.AddScoped<AuthenticationStateProvider, TokenAuthenticationStateProvider>();
services.AddAuthorizationCore();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}