Включение аутентификации Azure AD для пользовательского интерфейса Swagger, размещенного в Service Fabric

Мы включили Swagger для приложения веб-API, которое размещено в Azure Service Fabric. Мы хотим включить безопасность в пользовательском интерфейсе Swagger. Поэтому я следовал указанному ниже URL-адресу, который обеспечивает безопасность - https://blogs.msdn.microsoft.com/pratushb/2016/04/28/enable-swagger-to-authenticate-against-azure-ad/ https://github.com/domaindrivendev/Swashbuckle/issues/671 (ответ Александра-Токмакова)

Я мог видеть всплывающее окно «Доступные авторизации» и видеть успешную аутентификацию AAD на другой вкладке при нажатии кнопки «Авторизовать». Но после завершения аутентификации я вижу, что токен не возвращается к пользовательскому интерфейсу swagger, а вкладка аутентификации не закрывается.

Ниже приведен код, который я использовал. (Я создал два AAD, один для веб-служб, размещенных в Service Fabric, а другой для пользовательского интерфейса Swagger)

 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);
            }
        }
    }

person Thirumalai    schedule 05.03.2017    source источник


Ответы (1)


Я использую Auth0, но вот что у меня есть для OAuth2, которое мне подходит.

options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
    Type = "oauth2",
    Flow = "implicit",
    AuthorizationUrl = Path.Combine(auth0Settings["Authority"].Value, "authorize")
});

app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "docs";
    c.InjectOnCompleteJavaScript("/swagger-ui.js");
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Easy Streak API");
    c.ConfigureOAuth2(auth0Settings["ClientId"].Value, auth0Settings["ClientSecret"].Value, auth0Settings["Authority"].Value, "EasyStreak API");
});
person The Muffin Man    schedule 18.07.2017