OIDC在ASP中的流动.. NET Core 7.0 Web API对抗Google



我想使用OIDC流和Google作为ID提供者对我的Web API中的用户进行身份验证。

简而言之,我的应用程序由多个微服务组成,每个微服务都是一个Web API。所有服务中REST端点的认证都是通过JWT进行的。我有一个身份微服务,我希望它实现OIDC流,特别是实现以下三个REST端点。
  • login返回Challenge(或其URL);
  • logout端点。
  • callback是由Google调用的,应该从OIDC代码(包括ID和访问令牌)中提取用户信息;

大多数Microsoft AuthNZ模板要么主要是用UI元素构建的,要么利用第三方库,如Duende,我不能使用。

我可以重定向到谷歌使用Singin端点,虽然codenull当谷歌调用回重定向URI。所以,我不确定我的配置中缺少什么。

// Register services
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddGoogle(options =>
{
options.ClientId = "...";
options.ClientSecret = "...";
});
// Configure App
app.UseAuthentication();
app.UseAuthorization();

控制器。

[Route("api/v1/[controller]/[action]")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
[AllowAnonymous]
[HttpGet]
public IActionResult SignIn()
{
return new ChallengeResult(
"Google",
new AuthenticationProperties
{
IsPersistent = true,
RedirectUri = Url.Action("callback", "Identity") 
});
}
[AllowAnonymous]
[HttpGet(Name = "callback")]
public async Task<IActionResult> Callback(object code = null)
{
// code is null here.
}
}

您通常不单独使用AddGoogle,而是添加AddCookie()也这样应用程序就可以创建一个用户会话cookie。

.AddGoogle(options =>
{
options.ClientId = "...";
options.ClientSecret = "...";
});

查看这篇博文了解更多细节https://www.roundthecode.com/dotnet/how-to-add-google-authentication-to-a-asp-net-core-application

另外,确保将Cookies设置为默认身份验证方案

options.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;

Callback端点应该像下面这样实现。

[AllowAnonymous]
[HttpGet(Name = "callback")]
public async Task<IActionResult> callback()
{
var authResult = await HttpContext.AuthenticateAsync(
GoogleDefaults.AuthenticationScheme);
var claims = authResult.Principal.Identities
.FirstOrDefault().Claims.Select(claim => new
{
claim.Issuer,
claim.OriginalIssuer,
claim.Type,
claim.Value
});
return Content(claims.ToString());
}

我一直在使用cookie来获取身份验证结果,正如一些博客所建议的那样,如下所示,尽管这对我来说不起作用。

// An incorrect method of getting 
// authentication results in my use-case.
var authResult = await HttpContext.AuthenticateAsync(
CookieAuthenticationDefaults.AuthenticationScheme);

最新更新