【发布时间】:2017-07-18 14:37:36
【问题描述】:
我们为托管在 Azure Service Fabric 上的 Web API 应用程序启用了 Swagger。我们希望在 Swagger UI 上启用安全性。所以我按照下面的 url 启用安全性 - https://blogs.msdn.microsoft.com/pratushb/2016/04/28/enable-swagger-to-authenticate-against-azure-ad/ https://github.com/domaindrivendev/Swashbuckle/issues/671(来自 Oleksandr-Tokmakov 的回复)
我可以看到“可用授权”弹出窗口,并且单击“授权”按钮可以在另一个选项卡上看到 AAD 身份验证成功完成。但是一旦身份验证完成,我看到令牌没有返回到 swagger ui 并且身份验证选项卡没有关闭。
下面是我使用的代码。 (我创建了两个 AAD,一个用于托管在 Service Fabric 上的 Web 服务,另一个用于 Swagger UI)
config.EnableSwagger(
c =>
{
c.SingleApiVersion("v1", "Title of Service");
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit")
.AuthorizationUrl("https://login.microsoftonline.com/tenentId-guid/oauth2/authorize")
.Scopes(scopes =>
{
scopes.Add("user_impersonation", "Access Services Local Swagger Secure");
});
c.OperationFilter<AssignOAuth2SecurityRequirements>();
}
).EnableSwaggerUi(c =>
{
c.EnableOAuth2Support(
clientId: "Swagger AAD application Client Id",
clientSecret: "Swagger AAD application Key",
realm: "https://localhost:444/swagger/ui/o2c-html",
appName: "https://serviceslocal/swagger/", // Free text, no reference to AAD
scopeSeperator: "",
additionalQueryStringParams: new Dictionary<string, string>() { { "resource", "Web API AAD application Client Id" } }
);
}
);
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
// Correspond each "Authorize" role to an oauth2 scope
var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
.Select(filterInfo => filterInfo.Instance)
.OfType<AuthorizeAttribute>()
.SelectMany(attr => attr.Roles.Split(','))
.Distinct();
if (scopes.Any())
{
if (operation.security == null)
operation.security = new List<IDictionary<string, IEnumerable<string>>>();
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", scopes }
};
operation.security.Add(oAuthRequirements);
}
}
}
【问题讨论】:
标签: azure swagger azure-service-fabric swagger-ui