Blazor Maui 中使用 Google 登录的步骤与 Blazor WebAssembly 有些不同,需要额外的配置和代码。
首先,需要在 Google 开发者控制台中创建一个 OAuth 客户端 ID,并将“已授权的 JavaScript 源”字段设置为“localhost:8080”。然后,将以下代码添加到项目的 Program.cs 文件中:
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Controls.Xaml;
using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Extensions.DependencyInjection;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MyAppNamespace
{
public class Program
{
...
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp()
.ConfigureServices(services =>
{
// 添加 Google 登录服务
services.AddGoogleAuthentication(Configuration);
})
.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler();
});
return builder.Build();
}
}
}
其中,services.AddGoogleAuthentication(Configuration) 会添加 Google 登录服务,并需要在 appsettings.json 文件中添加以下配置:
{
"Google": {
"ClientId": "your_client_id_here.apps.googleusercontent.com",
"ClientSecret": "your_client_secret_here"
}
}
最后,在组件中使用以下代码实现登录:
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject NavigationManager Navigation
@inject SignOutSessionStateManager SignOutManager
@using MyAppNamespace.Auth
...
/
Welcome, @context.User.FindFirst(c => c.Type == "name")?.Value!
@{
var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);
var loginUrl = $"{Navigation.BaseUri}authentication/login?returnUrl={returnUrl}";
}
<