gpt4 book ai didi

authentication - SPA (Aurelia) + ASP.NET Core Web API + Google 身份验证

转载 作者:行者123 更新时间:2023-12-01 00:22:03 24 4
gpt4 key购买 nike

我的 SPA 应用程序(使用 Aurelia)调用我的 ASP.NET Core 2 Web API。我需要使用 Google OIDC 提供商对用户进行身份验证,并使用相同的方法保护 Web API。

目前我能够在客户端 (SPA) 端对用户进行身份验证并检索 id token 和访问 token 。对于每个 API 调用,我都会在 header 中发送访问 token 。

现在我不确定如何处理服务器端以验证 token 并授予或拒绝对 API 的访问。我按照官方文档如何添加外部登录提供程序,但它似乎只适用于服务器端 MVC 应用程序。

有什么简单的方法可以做到这一点吗?

我认为例如 IdentityServer4 可以支持这种情况,但在我看来它对于我需要做的事情来说太复杂了。毕竟我不需要自己的身份/授权服务器。

更新:

根据 Miroslav Popovic 的回答,我对 ASP.NET Core 2.0 的配置如下所示:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.Authority = "https://accounts.google.com";
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "accounts.google.com",
ValidAudience = "xxxxxxxxxxxxx.apps.googleusercontent.com",
ValidateAudience = true,
ValidateIssuer = true
};
});

services.AddMvc();
}

而在 Configure()我打电话 app.UseAuthentication() .

使用此设置时,我收到失败消息 No SecurityTokenValidator 可用于 token 。

更新 2:

我让它工作。服务器配置正确。问题是我正在向 API 发送 access_token 而不是 id_token。

最佳答案

由于您已经拥有访问 token ,因此使用它来添加身份验证应该不会太难。你需要一些类似的东西(未经测试):

// Inside Startup.cs, ConfigureServices method
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(
options =>
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "accounts.google.com",
ValidateAudience = false
};

options.MetadataAddress = "https://accounts.google.com/.well-known/openid-configuration";
options.TokenValidationParameters = tokenValidationParameters;
});

// Inside Startup.cs, Configure method
app.UseAuthentication(); // Before MVC middleware
app.UseMvc();

// And of course, on your controllers:
[Authorize]
public class MyApiController : Controller

Paul Rowe 的 This post 可能会有所帮助,但请注意,它是为 ASP.NET Core 1.x 编写的,并且身份验证 API 在 2.0 中略有变化。

这里也有很多关于 SO 的信息,比如 this question

关于authentication - SPA (Aurelia) + ASP.NET Core Web API + Google 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com