【问题标题】:SPA (Aurelia) + ASP.NET Core WebAPI + Google AuthenticationSPA (Aurelia) + ASP.NET Core WebAPI + Google 身份验证
【发布时间】:2018-05-30 15:52:58
【问题描述】:

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

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

现在我不确定如何处理服务器端来验证令牌并授予或拒绝对 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()

使用此设置时,我收到失败消息 没有可用于令牌的 SecurityTokenValidator。

更新 2:

我成功了。服务器配置正确。问题是我向 API 发送 access_token 而不是 id_token。

【问题讨论】:

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


    【解决方案1】:

    由于您已经拥有访问令牌,因此使用它来添加身份验证应该不会太难。您将需要这些方面的东西(未经测试):

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

    【讨论】:

    • 感谢您的帮助。我已经尝试过代码(我将其改编为 2.0),但服务器失败并显示以下消息:“没有可用于令牌的 SecurityTokenValidator。”我不知道为什么,我从 SPA 发布的令牌直接来自 Google。
    • 我已经用我当前的代码更新了原始问题。
    • 能否分享使用 MVC/Webform 进行 OIDC google 身份验证的链接?
    • @EngrUmair 也许这个文档页面可以提供帮助? docs.microsoft.com/en-us/aspnet/mvc/overview/security/…
    猜你喜欢
    • 2018-09-02
    • 2014-09-04
    • 1970-01-01
    • 2012-10-23
    • 2019-05-19
    • 2018-07-07
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多