ASP.NET 使用谷歌认证在回调时出现错误:oauth 状态丢失或无效。

huangapple go评论141阅读模式
英文:

ASP.NET with Google authentication throws error on callback: The oauth state was missing or invalid

问题

I can provide the translation for the code and text you've provided:

Program.cs

  1. #region 配置服务
  2. builder.Host.ConfigureLogging(builder => builder.AddDomainLogger());
  3. builder.Services.AddControllers();
  4. builder.Services.AddSwaggerGen(c =>
  5. {
  6. c.SwaggerDoc("v1", new OpenApiInfo { Title = "***", Version = "v1" });
  7. });
  8. // ... 添加一些服务
  9. builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  10. .AddCookie(options => options.LoginPath = "/api/authorization/login")
  11. .AddGoogle(options =>
  12. {
  13. options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  14. options.CallbackPath = "/api/authorization/google/signin";
  15. options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
  16. options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
  17. options.Scope.Add("email"); // 用于获取主要电子邮件地址
  18. options.Scope.Add("profile"); // 用于获取个人公共信息,如姓名、图片等。
  19. });
  20. #endregion
  21. var app = builder.Build();
  22. #region 配置应用程序
  23. // ... 一些逻辑
  24. if (app.Environment.IsDevelopment())
  25. {
  26. app.UseSwagger();
  27. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "***"));
  28. }
  29. app.UseAuthentication();
  30. app.UseAuthorization();
  31. app.UseHttpsRedirection();
  32. app.MapControllers();
  33. #endregion

GoogleAuthorizationController.cs

  1. [Route("api/authorization/google")]
  2. [ApiController]
  3. public class GoogleAuthorizationController : ControllerBase
  4. {
  5. [HttpGet]
  6. [Route("login")]
  7. public Task LoginGoogle()
  8. {
  9. return HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme, new AuthenticationProperties()
  10. {
  11. RedirectUri = Url.Action("SignInGoogle")
  12. });
  13. }
  14. [HttpGet]
  15. [Route("signin")]
  16. public async Task<IActionResult> SignInGoogle() // <- 无法达到这里
  17. {

If you need further assistance or have more specific questions, feel free to ask.

英文:

I'm developing a cookie authentication application with the ability to authorize through a Google account. I have a UI in React v18 and an ASP.NET Core 6 Web API. I created a web app in console.cloud.google.com and got the app credentials.

Authentication process with Google:

  1. user sends request from UI to API to authorize through google (.../google/login endpoint);
  2. the API redirects user to google authorization;
  3. after succeed authorization it sends user to .../google/signin endpoint (registered in google).

Well, 1 - 2 works well, but I have exception on callback endpoint after succeed authorization on google side. It's not inside my controller:

> Exception: The oauth state was missing or invalid.
> Unknown location
>
> Exception: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync()

ASP.NET 使用谷歌认证在回调时出现错误:oauth 状态丢失或无效。

I cannot understand how to fix it. I tried to change sign in schemas, callback paths etc, but it was useless. Here is my code:

Program.cs

  1. #region Configure services
  2. builder.Host.ConfigureLogging(builder =&gt; builder.AddDomainLogger());
  3. builder.Services.AddControllers();
  4. builder.Services.AddSwaggerGen(c =&gt;
  5. {
  6. c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;***&quot;, Version = &quot;v1&quot; });
  7. });
  8. // ... adding some services
  9. builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  10. .AddCookie(options =&gt; options.LoginPath = &quot;/api/authorization/login&quot;)
  11. .AddGoogle(options =&gt;
  12. {
  13. options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  14. options.CallbackPath = &quot;/api/authorization/google/signin&quot;;
  15. options.ClientId = builder.Configuration[&quot;Authentication:Google:ClientId&quot;];
  16. options.ClientSecret = builder.Configuration[&quot;Authentication:Google:ClientSecret&quot;];
  17. options.Scope.Add(&quot;email&quot;); // to get primary email address
  18. options.Scope.Add(&quot;profile&quot;); // to get personal public info like name, image etc.
  19. });
  20. #endregion
  21. var app = builder.Build();
  22. #region Configure app
  23. // ... some logic
  24. if (app.Environment.IsDevelopment())
  25. {
  26. app.UseSwagger();
  27. app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;***&quot;));
  28. }
  29. app.UseAuthentication();
  30. app.UseAuthorization();
  31. app.UseHttpsRedirection();
  32. app.MapControllers();
  33. #endregion

GoogleAuthorizationController.cs

  1. [Route(&quot;api/authorization/google&quot;)]
  2. [ApiController]
  3. public class GoogleAuthorizationController : ControllerBase
  4. {
  5. [HttpGet]
  6. [Route(&quot;login&quot;)]
  7. public Task LoginGoogle()
  8. {
  9. return HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme, new AuthenticationProperties()
  10. {
  11. RedirectUri = Url.Action(&quot;SignInGoogle&quot;)
  12. });
  13. }
  14. [HttpGet]
  15. [Route(&quot;signin&quot;)]
  16. public async Task&lt;IActionResult&gt; SignInGoogle() // &lt;- it can&#39;t reach it
  17. {

答案1

得分: 1

你不需要配置

  1. options.CallbackPath = &quot;/api/authorization/google/signin&quot;;

在你的配置中,options.CallbackPath 不是指向你的控制器/操作的路径。它只需要与你的第三方提供者(如Google等)中注册的路径相同。它指的是由身份验证中间件处理的唯一路径,而不是控制器路径,默认情况下是 signin-google,当完成后,它将重定向回你的控制器。

英文:

You don't need to configure

  1. options.CallbackPath = &quot;/api/authorization/google/signin&quot;;

in your configuration, The options.CallbackPath is not the path to your Controller/Action. It just must be the same as registered in your 3rd party provider (Google, or so...). It refers to a unique path handled by the auth middleware instead of controller, By default is signin-google, It will redirect back to your controller when it's done.

ASP.NET 使用谷歌认证在回调时出现错误:oauth 状态丢失或无效。

huangapple
  • 本文由 发表于 2023年6月8日 05:58:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定