public class AuthService : AuthenticationStateProvider
{
private readonly HttpClient httpClient;
private readonly ILocalStorageService localStorage;
public AuthService(HttpClient httpClient, ILocalStorageService localStorage)
{
this.httpClient = httpClient;
this.localStorage = localStorage;
}
public override async Task GetAuthenticationStateAsync()
{
var accessToken = await localStorage.GetItemAsync("access_token");
// 如果访问令牌未过期,从服务器检索用户信息
if (!string.IsNullOrEmpty(accessToken))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var userData = await httpClient.GetFromJsonAsync("api/UserData");
if (userData != null && !string.IsNullOrEmpty(userData.Email))
{
var claims = new[] { new Claim(ClaimTypes.Name, userData.Email) };
var identity = new ClaimsIdentity(claims, "GoogleAuth");
return new AuthenticationState(new ClaimsPrincipal(identity));
}
}
// 如果没有登录,返回未认证的AuthenticationState
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
}
}
private const string GoogleClientId = "";
private const string GoogleClientSecret = "";
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = GoogleClientId;
options.ClientSecret = GoogleClientSecret;
});
// 添加Jwt验证
services.AddAuthorizationCore(options =>
{
options.AddPolicy("JwtAuth", policy =>
{
policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
services.AddControllers();
services.AddHttpClient();
services.AddHttpContextAccessor();
services.Add BlazoredLocalStorage();
services.AddScoped();
services.AddScoped();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
@inject AuthService authService
...
Hello, @context.User.Identity.Name!
Please log in.
Login
...
@code {
private AuthenticationState authState;
protected override async Task OnInitializedAsync()
{
authState = await authService.GetAuthenticationStateAsync();
authService.AuthStateChanged