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

标签 authentication single-page-application aurelia asp.net-core-webapi

我的 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/

相关文章:

使用 NTAG 424 DNA TT 的身份验证提示

javascript - 如何使用 http-client 与 Aurelia 请求跨域

python - 通过外部提供商进行 Django 身份验证

java - Spring 安全 "Remember Me"复选框

javascript - Vue.js 根据条件绑定(bind)到类

javascript - 使用 TypeScript 定义 Durandal ViewModel

html5 - 是否在WebSite项目中使用grunt和bower进行HTML5开发,还是在Visual Studio 2015中创建HTML5 Web应用程序?

aurelia - 使用 Aurelia <content> 元素

jspm - Aurelia 验证插件

Facebook、谷歌和我自己的身份验证的数据库模式