如何保护网络 api 以验证客户端应用程序生成的 openid 令牌?

How to secure web api to validate openid token generated by Client application?

客户端应用程序 的启动 up.cs 文件中的 OpenId Connect 配置:

services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()

            .AddOpenIdConnect(options =>
            {
                options.ClientId = azureAdConfig.ClientId;
                options.ClientSecret = azureAdConfig.ClientSecret;
                options.Authority = string.Format(com/, azureAdConfig.Tenant);
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.Resource = azureAdConfig.ResourceURI_Graph;
                options.Events = new AuthEvents(azureAdConfig, connectionStringsConfig);
            });

我想将令牌传递给网络 api。

But how to secure web api and validate the token in api project?

我同意大多数文档似乎都侧重于网络应用场景。假设您也在那里使用 .Net Core,对于 APIs,这是使用此包的功能的情况:

  • Microsoft.AspNetCore.Authentication.JwtBearer
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
})

有关工作示例,请参阅下面的资源 - 代码可以与任何授权服务器相同的方式编写:

AZURE 广告代币

这些有一些特定的要求。在自定义 APIs 中要避免的事情是在 JWT header 中带有随机数字段的 JWT,因为这些仅供 Microsoft 自己的 APIs

使用

我的 blog post 有一些关于如何解决这个问题的细节,通过注册一个逻辑 API 服务来代表一个或多个 API,然后公开你自己的 API范围。