You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor Server应用中添加Google认证与AAD共存?

多账号登录(AAD + Google)实现方案

1. 调整认证服务配置

首先需要将默认认证方案改为Cookie,因为多身份提供商场景下,Cookie作为统一的会话存储方案,外部认证(AAD/Google)作为验证来源。修改Program.cs中的认证配置:

using Microsoft.AspNetCore.Authentication.Cookies;

// 配置认证服务
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie() // 添加Cookie认证
    .AddGoogle(options =>
    {
        options.ClientId = Configuration["GoogleAuthentication:ClientId"];
        options.ClientSecret = Configuration["GoogleAuthentication:ClientSecret"];
        // 可选:自定义回调路径,需与Google控制台设置一致,默认是/signin-google
        // options.CallbackPath = "/google-login-callback";
    })
    .AddMicrosoftIdentityWebApp(options =>
    {
        Configuration.Bind(Microsoft.Identity.Web.Constants.AzureAd, options);
    });

2. 添加控制器处理登录流程

由于Blazor Server需要触发服务器端的认证挑战,需创建一个AccountController来处理外部登录的请求和回调:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

public class AccountController : Controller
{
    // 触发指定提供商的登录流程
    [HttpGet("login/{provider}")]
    public IActionResult ExternalLogin(string provider)
    {
        // 登录成功后的回调地址
        var redirectUrl = Url.Action("ExternalLoginCallback", "Account");
        var authProperties = new AuthenticationProperties { RedirectUri = redirectUrl };
        
        // 发起认证挑战
        return Challenge(authProperties, provider);
    }

    // 登录回调处理
    [HttpGet("login/callback")]
    public async Task<IActionResult> ExternalLoginCallback()
    {
        // 验证登录结果
        var authResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        if (!authResult.Succeeded)
        {
            // 登录失败,跳回登录页
            return RedirectToPage("/Login");
        }

        // 可选:获取用户身份信息,执行自定义业务逻辑(如关联本地用户)
        var userClaims = authResult.Principal.Claims;

        // 登录成功,跳转到主页
        return RedirectToPage("/Index");
    }
}

同时确保端点映射包含控制器路由,在Program.cs的UseEndpoints中添加:

app.UseEndpoints(endpoints =>
{
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");
    // 添加控制器路由
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Account}/{action=ExternalLogin}/{provider?}");
});

3. 在Blazor UI中添加登录入口

创建登录组件(如Login.razor),添加两个登录按钮,分别触发AAD和Google的登录流程:

<div class="login-container d-flex flex-column gap-3 p-4">
    <button class="btn btn-primary" 
            @onclick="() => NavigationManager.NavigateTo("/login/Microsoft", forceLoad: true)">
        使用Microsoft账号登录
    </button>
    <button class="btn btn-danger" 
            @onclick="() => NavigationManager.NavigateTo("/login/Google", forceLoad: true)">
        使用Google账号登录
    </button>
</div>

@code {
    [Inject]
    private NavigationManager NavigationManager { get; set; }
}

注意:必须设置forceLoad: true,因为外部登录需要触发服务器端的认证流程,客户端路由无法直接处理,强制刷新才能正确跳转。

4. Google控制台配置验证

确保Google开发者控制台中,OAuth 2.0客户端ID的已授权重定向URI包含默认回调路径(或你自定义的路径),例如本地开发环境:
https://localhost:5001/signin-google

内容的提问来源于stack exchange,提问作者DaPanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:03:35