Веб-API 2, Swagger и IdentityServer3

Я пытаюсь настроить веб-API с помощью Swagger и IdentityServer и не могу понять, как заставить Swagger работать правильно.

Мое приложение React работает с IdentityServer, и мне удалось заставить работать пользовательский интерфейс, но когда я пытаюсь активировать аутентификацию, я всегда получаю ошибку «insufficient_scope».

Вот мой конфиг:

Клиент

public static IEnumerable<Client> Get()
{
    return new[]
    {
        new Client
        {
            ClientId = "ipassportimplicit",
            ClientName = "iPassport (Implicit)",
            Flow = Flows.Implicit,
            AllowAccessToAllScopes = true,
            //redirect = URI of the React application callback page
            RedirectUris = new List<string>
            {
                Constants.iPassportReact + "callback.html"
            }
        },
        new Client
        {
            ClientId = "swaggerui",
            ClientName = "Swagger (Implicit)",
            Flow = Flows.Implicit,
            AllowAccessTokensViaBrowser = true,
            PostLogoutRedirectUris = new List<string>
            {
                "http://localhost:53633/swagger/"
            },
            AllowAccessToAllScopes = true,
            RedirectUris = new List<string>
            {
                "http://localhost:53633/swagger/ui/o2c-html"
            }
        }
    };
}

Сфера

public static IEnumerable<Scope> Get()
{
    return new List<Scope>
        {                    
            new Scope
            { 
                Name = "passportmanagement",
                DisplayName = "Passport Management",
                Description = "Allow the application to manage passports on your behalf.",
                Type = ScopeType.Resource 
            },
            new Scope
            {
                Name = "swagger",
                DisplayName = "Swagger UI",
                Description = "Display Swagger UI",
                Type = ScopeType.Resource
            }
        };
}

SwaggerConfig

public static void Register(HttpConfiguration config)
{
    var thisAssembly = typeof(SwaggerConfig).Assembly;

    config
        .EnableSwagger(c =>
            {
                c.SingleApiVersion("v2", "api_iPassport");

                c.OAuth2("oauth2")
                    .Description("OAuth2 Implicit Grant")
                    .Flow("implicit")
                    .AuthorizationUrl(Constants.iPassportSTSAuthorizationEndpoint)
                    .TokenUrl(Constants.iPassportSTSTokenEndpoint)                            
                    .Scopes(scopes =>
                    {
                        scopes.Add("swagger", "Swagger UI");
                    });

                c.OperationFilter<AssignOAuth2SecurityRequirements>();
            })
        .EnableSwaggerUi(c => 
            {   
                c.EnableOAuth2Support("swaggerui", "swaggerrealm", "Swagger UI");
            });
}

Фильтр операций

public class AssignOAuth2SecurityRequirements : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline();
        var allowsAnonymous = actFilters.Select(f => f.Instance).OfType<OverrideAuthorizationAttribute>().Any();
        if (allowsAnonymous)
            return; // must be an anonymous method


        //var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
        //    .Select(filterInfo => filterInfo.Instance)
        //    .OfType<AllowAnonymousAttribute>()
        //    .SelectMany(attr => attr.Roles.Split(','))
        //    .Distinct();

        if (operation.security == null)
            operation.security = new List<IDictionary<string, IEnumerable<string>>>();

        var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
    {
        {"oauth2", new List<string> {"swagger"}}
    };

        operation.security.Add(oAuthRequirements);
    }
}

Заголовки ответа

{
  "date": "Fri, 12 May 2017 03:37:08 GMT",
  "www-authenticate": "Bearer error=\"insufficient_scope\"",
  "x-sourcefiles": "=?UTF-8?B?TzpcTG9jYWwgV29ya3NwYWNlXFZTVFMgSUJNXFJlcG9zXFdlYkFQSVxhcGlfaVBhc3Nwb3J0XGFwaV9pUGFzc3BvcnRcYXBpXFVzZXJcR2V0?=",
  "server": "Microsoft-IIS/10.0",
  "x-powered-by": "ASP.NET",
  "content-length": "0",
  "content-type": null
}

Я ничего не вижу? Вся помощь приветствуется!

Спасибо


person Bruno    schedule 12.05.2017    source источник


Ответы (1)


Моя проблема заключалась в моем классе Startup.cs веб-API, в котором я не добавил требуемую область в

public void ConfigureAuth(IAppBuilder app)
{
    var options = new IdentityServerBearerTokenAuthenticationOptions()
    {
        Authority = Constants.iPassportSTS,
        RequiredScopes = new[] { "passportmanagement", "swagger" }
    };

    app.UseIdentityServerBearerTokenAuthentication(options);
}
person Bruno    schedule 15.05.2017