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

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

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

#region 配置服务

builder.Host.ConfigureLogging(builder => builder.AddDomainLogger());

builder.Services.AddControllers();

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "***", Version = "v1" });
});

// ... 添加一些服务

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => options.LoginPath = "/api/authorization/login")
    .AddGoogle(options =>
    {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.CallbackPath = "/api/authorization/google/signin";

        options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
        options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];

        options.Scope.Add("email"); // 用于获取主要电子邮件地址
        options.Scope.Add("profile"); // 用于获取个人公共信息,如姓名、图片等。
    });

#endregion

var app = builder.Build();

#region 配置应用程序

// ... 一些逻辑

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "***"));
}

app.UseAuthentication();

app.UseAuthorization();

app.UseHttpsRedirection();

app.MapControllers();

#endregion

GoogleAuthorizationController.cs

[Route("api/authorization/google")]
[ApiController]
public class GoogleAuthorizationController : ControllerBase
{
    [HttpGet]
    [Route("login")]
    public Task LoginGoogle()
    {
        return HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme, new AuthenticationProperties()
        {
            RedirectUri = Url.Action("SignInGoogle")
        });
    }

    [HttpGet]
    [Route("signin")]
    public async Task<IActionResult> SignInGoogle() // <- 无法达到这里
    {  

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


#region Configure services

builder.Host.ConfigureLogging(builder =&gt; builder.AddDomainLogger());

builder.Services.AddControllers();

builder.Services.AddSwaggerGen(c =&gt;
{
    c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;***&quot;, Version = &quot;v1&quot; });
});

// ... adding some services

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =&gt; options.LoginPath = &quot;/api/authorization/login&quot;)
    .AddGoogle(options =&gt;
    {
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.CallbackPath = &quot;/api/authorization/google/signin&quot;;

        options.ClientId = builder.Configuration[&quot;Authentication:Google:ClientId&quot;];
        options.ClientSecret = builder.Configuration[&quot;Authentication:Google:ClientSecret&quot;];

        options.Scope.Add(&quot;email&quot;); // to get primary email address
        options.Scope.Add(&quot;profile&quot;); // to get personal public info like name, image etc.
    });

#endregion

var app = builder.Build();

#region Configure app

// ... some logic

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =&gt; c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;***&quot;));
}

app.UseAuthentication();

app.UseAuthorization();

app.UseHttpsRedirection();

app.MapControllers();

#endregion

GoogleAuthorizationController.cs


[Route(&quot;api/authorization/google&quot;)]
[ApiController]
public class GoogleAuthorizationController : ControllerBase
{
    [HttpGet]
    [Route(&quot;login&quot;)]
    public Task LoginGoogle()
    {
        return HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme, new AuthenticationProperties()
        {
            RedirectUri = Url.Action(&quot;SignInGoogle&quot;)
        });
    }

    [HttpGet]
    [Route(&quot;signin&quot;)]
    public async Task&lt;IActionResult&gt; SignInGoogle() // &lt;- it can&#39;t reach it
    {  

答案1

得分: 1

你不需要配置

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

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

英文:

You don't need to configure

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:

确定