如何将 swagger 与 Azure Active Directory OAuth 集成

How to integrate swagger with Azure Active Directory OAuth

我正在尝试使用 Azure Active Directory V2 在我的 AspNetCore 2.1 应用程序中设置 Swagger,但我似乎无法正确设置。我能够配置设置,以便 swagger 提示、重定向并成功验证我的 client/user,但是当将不记名令牌传递到服务器时会导致错误 Bearer error="invalid_token", error_description="The signature is invalid"。我已经为项目创建了一个 GitHub 存储库,我正在尝试使用它的所有配置 (https://github.com/alucard112/auth-problem)

通过将资源设置为 AAD 应用程序的客户端 ID,我已设法让 V1 端点正常工作,这导致 JWT 令牌的 'aud' 设置为应用程序客户端 ID。在 V2 端点中,'aud' 被设置为我认为是图形 API 资源“00000003-0000-0000-c000-000000000000”。我相信这是我目前的问题,尽管我不是 100% 确定。 V2 端点似乎没有办法像 V1 那样定义受众,除非我这边有一些疏忽。

我的启动文件结构如下:

身份验证设置如下:

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));


            services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
            {
                options.Authority = $"https://login.microsoftonline.com/{tenantId}";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // In multi-tenant apps you should disable issuer validation:
                    ValidateIssuer = false,
                    // In case you want to allow only specific tenants,
                    // you can set the ValidIssuers property to a list of valid issuer ids
                    // or specify a delegate for the IssuerValidator property, e.g.
                    // IssuerValidator = (issuer, token, parameters) => {}
                    // the validator should return the issuer string
                    // if it is valid and throw an exception if not
                };
            });

Swagger 设置如下:

 services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "Protected Api",
                });

                c.OperationFilter<SecurityRequirementsOperationFilter>();

                //IMATE - StevensW
                // Define the OAuth2.0 scheme that's in use (i.e. Implicit Flow)
                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize",
                    TokenUrl = $"https://login.microsoftonline.com/common/{tenantId}/v2.0/token",
                    Scopes = new Dictionary<string, string>
                   {
                       { "openid", "Unsure" },
                       { "profile", "Also Unsure" }
                   }
                });
            });
 app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.OAuthClientId(Configuration.GetValue<string>("AzureAd:ClientId"));
                c.OAuthAppName("Protected API");

                //c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
                //c.OAuthClientSecret(Configuration.GetValue<string>("AzureAd:ClientId"));
            });

我希望配置 swagger UI 以使用 AAD 的 V2 端点并允许多租户登录,从而允许执行成功验证的 API 调用。任何帮助或指导将不胜感激。

我最终解决了我遇到的问题。经历 this post 帮助我理解了我的错误。

第一个错误是我实际注册了 AAD 应用程序。我没有在 "Expose an API" 下设置应用程序的范围。因为他们在 V2 中弃用了资源 属性,所以您设置资源的方式是创建格式为 api"//{application ID}/{scope_name} 的范围。之后我进行了此更改,我的 AAD 应用程序现在已正确配置。

之后,我需要在我的启动文件中添加一个额外的部分:

return services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
             {
                 // This is an Azure AD v2.0 Web API
                 options.Authority += "/v2.0";

                 // The valid audiences are both the Client ID (options.Audience) and api://{ClientID}
                 options.TokenValidationParameters.ValidAudiences = new string[] { options.Audience, $"api://{options.Audience}" };


                 options.TokenValidationParameters.ValidateIssuer = false;
             });

注意:如果有人感兴趣,上面的 link 提供了关闭发行者验证的替代解决方案。

我的 AppSettings 文件也得到了简化,只需定义 Instance、TenantId 和 ClientId。

然后从大摇大摆的角度来看,我只需要向安全定义添加一个额外的范围,以匹配我在 AAD 应用程序中创建的范围。

          c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
                    TokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    Scopes = new Dictionary<string, string>
                   {
                       { "openid", "Sign In Permissions" },
                       { "profile", "User Profile Permissions" },
                       { $"api://{clientId}/access_as_user", "Application API Permissions" }
                   }
                });

进行这些更改后,我的应用程序现在可以按预期工作了。

对于 v2 端点,将 AAD 清单中的 accessTokenAcceptedVersion 从 null 更新为 2。它将起作用。