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

Blazor服务器应用Google登录取消时抛出AuthenticationFailureException的处理

解决Blazor服务器端Google登录取消时的AuthenticationFailureException捕获问题

核心原因

发起登录的方法会直接重定向到Google登录页,该方法执行完毕后就结束了;用户取消登录后,Google会回调默认的/signin-google端点,这个请求由ASP.NET Core认证中间件处理,此时抛出的异常无法被之前的try/catch捕获,且自定义的/signin-google处理程序会被认证中间件的内置处理逻辑覆盖,无法命中。

解决方案:利用认证事件钩子处理失败回调

通过配置Google认证的OnRemoteFailure事件,在认证中间件处理失败请求时直接拦截并跳转至自定义错误页面,具体步骤如下:

  1. 修改Program.cs中的Google认证配置
    在AddGoogle配置中添加事件处理逻辑,识别用户取消登录的access_denied错误,并重定向到自定义失败页面:
builder.Services.AddAuthentication()
    .AddGoogle(options =>
    {
        options.ClientId = "你的Google ClientId";
        options.ClientSecret = "你的Google ClientSecret";
        
        options.Events = new OAuthEvents
        {
            OnRemoteFailure = context =>
            {
                // 匹配用户取消登录的错误场景
                if (context.Failure is AuthenticationFailureException 
                    && context.Request.Query.TryGetValue("error", out var error) 
                    && error == "access_denied")
                {
                    // 重定向到自定义登录失败页面
                    context.Response.Redirect("/LoginFailed");
                    // 终止后续中间件处理,避免抛出异常
                    context.HandleResponse();
                }
                return Task.CompletedTask;
            }
        };
    });
  1. 创建自定义登录失败页面
    在Blazor项目中新建LoginFailed.razor页面,添加提示内容:
@page "/LoginFailed"

<h3>登录失败</h3>
<p>你已取消Google登录操作,若需要请重新尝试登录。</p>
<button class="btn btn-primary" @onclick="NavigateToLogin">返回登录页</button>

@code {
    private void NavigateToLogin()
    {
        NavigationManager.NavigateTo("/Login");
    }
}

备选方案:全局异常捕获重定向

若需要统一处理所有AuthenticationFailureException,可以添加自定义异常处理中间件(需放在认证中间件之前):

app.Use(async (context, next) =>
{
    try
    {
        await next();
    }
    catch (AuthenticationFailureException ex)
    {
        // 判断是否为用户取消登录的场景
        if (ex.InnerException?.Message == "资源所有者或远程服务器拒绝了访问。")
        {
            context.Response.Redirect("/LoginFailed");
        }
        else
        {
            // 其他认证失败场景可另行处理
            throw;
        }
    }
});

// 确保认证中间件在异常处理中间件之后
app.UseAuthentication();
app.UseAuthorization();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:52:09