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

ASP.NET Core中Google OAuth登录报错:oauth state缺失或无效求助

集成Google OAuth登录时遇到"The oauth state was missing or invalid"错误

错误信息

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
执行请求时发生未处理的异常。
Microsoft.AspNetCore.Authentication.AuthenticationFailureException: 处理远程登录时遇到错误。
---> Microsoft.AspNetCore.Authentication.AuthenticationFailureException: OAuth状态缺失或无效。
--- 内部异常堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

相关代码

Program.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.HttpOverrides;
using Project.Hubs;

var builder = WebApplication.CreateBuilder(args);

// 向容器添加服务
builder.Services.AddRazorPages();

// Google OAuth配置
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
    {
        options.ClientId = builder.Configuration.GetSection("GoogleKeys:ClientId").Value;
        options.ClientSecret = builder.Configuration.GetSection("GoogleKeys:ClientSecret").Value;
        options.ClaimActions.MapJsonKey("urn:google:picture", "picture", "url");
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });

builder.Services.AddRazorPages();
builder.Services.AddSession();
builder.Services.AddSignalR();

var app = builder.Build();

// 配置HTTP请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // 默认HSTS值为30天。生产环境可能需要调整,详见https://aka.ms/aspnetcore-hsts。
    app.UseHsts();
}
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
app.UseSession();

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
//app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.MapHub<ChatHub>("/chathub");
app.MapHub<ChatWithSpecifyUser>("/chatWithUser");

app.Run();

LoginWithGoogleModel.cs(Razor Page模型)

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Project.Pages.Auth
{
    public class LoginWithGoogleModel : PageModel
    {
        public async Task OnGet()
        {
            await HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme,
                new AuthenticationProperties
                {
                    RedirectUri = Url.Page("./GoogleResponse")
                });
        }
    }
}

GoogleResponseModel.cs(Razor Page模型)

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
using Project.Services;
using Project.ViewModels.Auth;
using NuGet.Protocol;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Identity;

namespace Project.Pages.Auth
{
    public class GoogleResponseModel : PageModel
    {
        private readonly AuthService authService = new AuthService();
        public async Task<IActionResult> OnGet()
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            var Claims = result.Principal.Identities.FirstOrDefault().Claims
                .Select(claim => new
                {
                    claim.Value,
                    claim.Issuer,
                    claim.OriginalIssuer,
                    claim.Type,
                });
            string email = Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Email).Value;
            string name = Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name).Value;
            LoginResponse response = authService.GetLoginResponseFromEmail(email, name);
            HttpContext.Session.SetString("user", response.ToJson());

            return Redirect("chat");
        }
    }
}

我是开发新手,在给应用集成Google OAuth登录功能时碰到了这个问题。已经在谷歌上搜了各种解决方案,折腾好几个小时还是没修好,希望有人能帮忙解决。

内容的提问来源于stack exchange,提问作者Nghĩa Đỗ Minh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 08:47:17