我正在尝试使用 JWT(不带 cookie)在我的 ASP.NET Core 8 API 中实现 Google 身份验证,但我一直收到此错误:
InvalidOperationException:为方案“Bearer”注册的身份验证处理程序是“JwtBearerHandler”,无法用于 SignInAsync。您是否忘记调用 AddAuthentication().AddCookie("Cookies") 和 SignInAsync("Cookies",...)?
这是我的代码:
Program.cs
:
var key = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"]);
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddGoogle(options =>
{
var googleAuth = builder.Configuration.GetSection("GoogleAuth");
options.ClientId = googleAuth["ClientId"];
options.ClientSecret = googleAuth["ClientSecret"];
options.CallbackPath = "/auth/signin-google";
options.SaveTokens = true;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
// Validation parameters...
};
});
控制器:
[HttpGet("login")]
public IActionResult Login()
{
var redirectUrl = Url.Action(nameof(GoogleResponse),"Auth");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[HttpGet("signin-google")]
public async Task<IActionResult> GoogleResponse()
{
// Error occurs here...
var result = await HttpContext.AuthenticateAsync(GoogleDefaults.AuthenticationScheme);
}