谷歌身份验证:"The oauth state was missing or invalid. Unknown location"



我正在尝试在Core 3上设置Google Auth ASP.NET 但出现此错误:

oauth 状态缺失或无效。未知位置

我的启动.cs文件如下所示:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllersWithViews()
.AddRazorRuntimeCompilation();
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IPaddleSettingsService, PaddleSettingsService>();
services.AddScoped<IPaymentProviderService, PaddlePaymentProviderService>();
services.Configure<AppConstants>(Configuration);
services
.AddAuthentication(o =>
{
o.DefaultScheme = "Application";
o.DefaultSignInScheme = "External";
})
.AddCookie("Application")
.AddCookie("External")
.AddGoogle(o =>
{
o.ClientId = Configuration["GoogleClientId"];
o.ClientSecret = Configuration["GoogleClientSecret"];
o.CallbackPath = new PathString("/a/signin-callback");
o.ReturnUrlParameter = new PathString("/");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}

控制器:

[Route("a")]
/*[Route("Account")]*/ //Adding additional Account route to controller solves the problem. Why?
public class AccountController : Controller
{
private readonly IOptions<AppConstants> _appConstants;
private readonly IPaymentProviderService _paymentProvider;
public AccountController(IOptions<AppConstants> appConstants, IPaymentProviderService paymentProvider)
{
_appConstants = appConstants;
_paymentProvider = paymentProvider;
}

[Route("signin-google")]
public IActionResult Signin(string returnUrl)
{
return new ChallengeResult(
GoogleDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(GoogleCallback), new { returnUrl })
});
}
[Route("signin-callback")]
public async Task<IActionResult> GoogleCallback(string returnUrl)
{
var authenticateResult = await HttpContext.AuthenticateAsync("External");
if (!authenticateResult.Succeeded) return LocalRedirect("/#signinerr");
var emailClaim = authenticateResult.Principal.FindFirst(ClaimTypes.Email);
var activeSubscriptions = await _paymentProvider.GetUserActiveSubscriptions(emailClaim.Value);
if (activeSubscriptions.Length != 0)
{
var activeSubscription = activeSubscriptions.First(a => a.State == "active");
SetCookies(emailClaim.Value, activeSubscription.UserId, activeSubscription.SubscriptionId);
return LocalRedirect("/");
}
ClearCookies();
return LocalRedirect("/#signinerr");
}              
}

谷歌中的授权网址如下,它与我的本地网址完美匹配:

http://localhost:5000/a/signin-callback

当我选择一个帐户来授权谷歌时,我收到错误,但如果我添加

[Route("Account")]

到控制器的路由,然后一切正常。我不明白为什么添加帐户路由会有所不同?知道引擎盖下发生了什么吗?

我遇到了同样的问题,最后,我设法解决了它。问题是googleOptions.CallbackPath不是API 端点,登录后将继续执行。 它是一个内部终结点,用于某些内部身份验证逻辑。 如果要更改回调终结点,则必须以其他方式执行此操作。

更多详情请见第 https://github.com/dotnet/aspnetcore/issues/22125 期

但是长话短说 - 保持googleOptions.CallbackPath不变,并使用AuthenticationProperties将返回 url 作为参数传递

解决错误消息"oauth 状态缺失或无效"的问题。未知位置",你只需要确保你的代码的回调URL可以访问。在我的应用程序中,aspnet 核心回调 URL 在回调路径的末尾需要"/",如下所示:

options.CallbackPath = "/signin/callback/";
options.AccessDeniedPath = "/home";

并且您必须在OAuth注册应用程序中更新,例如大本营或谷歌,使用正确的路径进行编辑

谢谢,希望可以解决您的问题

相关内容

最新更新