5

I’m using Swashbuckle (5.3.2) and it generates a nice API documentation.

To clarify my problem, I set up a small example project with no real meaning.

The API can only be used with a valid API key. For that I introduced an ApiKeyFilter which validates the api_key and read out corresponding roles.

ApiKeyFilter

public class ApiKeyFilter : IAuthenticationFilter
{
    private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
    private readonly string authenticationScheme = "Bearer";
    private readonly string queryStringApiKey = "api_key";

    public bool AllowMultiple
    {
        get { return false; }
    }

    public ApiKeyFilter()
    {
        if (allowedApps.Count == 0)
        {
            allowedApps.Add("PetLover_api_key", new []{"PetLover"});
            allowedApps.Add("CarOwner_api_key", new []{"CarOwner"});
            allowedApps.Add("Admin_api_key", new []{"PetLover","CarOwner"});
        }
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var req = context.Request;
        Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
        string rawAuthzHeader = null;
        if (queryStrings.ContainsKey(queryStringApiKey))
        {
            rawAuthzHeader = queryStrings[queryStringApiKey];
        }
        else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
        {
            rawAuthzHeader = req.Headers.Authorization.Parameter;
        }
        if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
        {
            var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
            context.Principal = currentPrincipal;
        }
        else
        {
            context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
        }

        return Task.FromResult(0);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        context.Result = new ResultWithChallenge(context.Result);
        return Task.FromResult(0);
    }


}

public class ResultWithChallenge : IHttpActionResult
{
    private readonly string authenticationScheme = "amx";
    private readonly IHttpActionResult next;

    public ResultWithChallenge(IHttpActionResult next)
    {
        this.next = next;
    }

    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = await next.ExecuteAsync(cancellationToken);

        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(authenticationScheme));
        }

        return response;
    }
}

The controller/resources can only be accessed if the requester has the corresponding role.

PetController

[Authorize(Roles = "PetLover")]
[RoutePrefix("api/pets")]
public class PetController : ApiController
{
    // GET api/pet
    [Route]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/pet/5
    [Route("{id:int}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/pet
    [Route]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/pet/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/pet/5
    public void Delete(int id)
    {
    }
}

CarController

[RoutePrefix("api/cars")]
public class CarController : ApiController
{
    // GET api/car
    [AllowAnonymous]
    [Route]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/car/5
    [Authorize(Roles = "CarOwner")]
    [Route("{id:int}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/car
    [Authorize(Roles = "CarOwner")]
    [Route]
    public void Post([FromBody]string value)
    {
    }
}


WebApiConfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Filters.Add(new ApiKeyFilter());

            //config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());
        }
    }

So far so good. No problem here.

Question:


Now I want that the ‘User’ roles are taken into account during the API generation. I only want to display the resources and actions in the documentation which the user can consume with this api_key.

The output should somehow look like (/swagger/ui/index?api_key=XXX):

  1. Admin_api_key:

    • Car
      • get /api/cars
      • post /api/cars
      • get /api/cars/{id}
    • Pet
      • get /api/pets
      • post /api/pets
      • get /api/pets/{id}
  2. CarOwner_api_key:

    • Car
      • get /api/cars
      • post /api/cars
      • get /api/cars/{id}
  3. PetLover_api_key:

    • Car
      • get /api/cars
    • Pet
      • get /api/pets
      • post /api/pets
      • get /api/pets/{id}
  4. invalid_api_key:

    • Nothing to display

I don’t have access to the HttpRequest during the API specification generation to read out any query string or any header information.

I already had a look into a DelegatingHandler but I have trouble to read out the Principal in any Swashbuckle filter (OperationFilter, DocumentFilter) and I’m also not able to read out the Principal in a CustomProvider.

public class CustomAuthenticationMessageHandler : DelegatingHandler
    {
        private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
        private readonly string authenticationScheme = "Bearer";
        private readonly string queryStringApiKey = "api_key";

        public bool AllowMultiple
        {
            get { return false; }
        }

        public CustomAuthenticationMessageHandler()
        {
            if (allowedApps.Count == 0)
            {
                allowedApps.Add("PetLover_api_key", new[] {"PetLover"});
                allowedApps.Add("CarOwner_api_key", new[] {"CarOwner"});
                allowedApps.Add("Admin_api_key", new[] {"PetLover", "CarOwner"});
            }
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var req = request;
            Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
            string rawAuthzHeader = null;
            if (queryStrings.ContainsKey(queryStringApiKey))
            {
                rawAuthzHeader = queryStrings[queryStringApiKey];
            }
            else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                rawAuthzHeader = req.Headers.Authorization.Parameter;
            }
            if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
            {
                var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
                request.GetRequestContext().Principal = currentPrincipal;
            }
            else
            {

            }

            return await base.SendAsync(request, cancellationToken);
        }
    }



I found some similar question/issues but no real answer.
Web API Documentation using swagger
Restrict access to certain API controllers in Swagger using Swashbuckle and ASP.NET Identity
{hxxps://}github.com/domaindrivendev/Swashbuckle/issues/334
{hxxps://}github.com/domaindrivendev/Swashbuckle/issues/735
{hxxps://}github.com/domaindrivendev/Swashbuckle/issues/478

1 Answer 1

6

I now found a solution which works for me.

I used the CustomAuthenticationMessageHandler (same as in my question) to put the rules into the HttpContext.

public class CustomAuthenticationMessageHandler : DelegatingHandler
    {
        private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
        private readonly string authenticationScheme = "Bearer";
        private readonly string queryStringApiKey = "api_key";

        public bool AllowMultiple
        {
            get { return false; }
        }

        public CustomAuthenticationMessageHandler()
        {
            if (allowedApps.Count == 0)
            {
                allowedApps.Add("PetLover_api_key", new[] {"PetLover"});
                allowedApps.Add("CarOwner_api_key", new[] {"CarOwner"});
                allowedApps.Add("Admin_api_key", new[] {"PetLover", "CarOwner"});
            }
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var req = request;
            Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
            string rawAuthzHeader = null;
            if (queryStrings.ContainsKey(queryStringApiKey))
            {
                rawAuthzHeader = queryStrings[queryStringApiKey];
            }
            else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                rawAuthzHeader = req.Headers.Authorization.Parameter;
            }
            if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
            {
                var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
                request.GetRequestContext().Principal = currentPrincipal;
            }
            else
            {

            }

            return await base.SendAsync(request, cancellationToken);
        }
    }

I introduced an custom Swashbuckle IDocumentFilter which reads out the rules from the HttpContext and remove the actions and resources from the SwaggerDocument which are not allowed for this rules (based on api_key).

public class AuthorizeRoleFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            IPrincipal user = HttpContext.Current.User;

            foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
            {
                var authorizeAttributes = apiDescription
                    .ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>().ToList();
                authorizeAttributes.AddRange(apiDescription
                    .ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AuthorizeAttribute>());

                if (!authorizeAttributes.Any())
                    continue;

                var roles =
                    authorizeAttributes
                        .SelectMany(attr => attr.Roles.Split(','))
                        .Distinct()
                        .ToList();
                if (!user.Identity.IsAuthenticated || !roles.Any(role => user.IsInRole(role) || role == ""))
                {
                    string key = "/" + apiDescription.RelativePath;
                    PathItem pathItem = swaggerDoc.paths[key];
                    switch (apiDescription.HttpMethod.Method.ToLower())
                    {
                        case "get":
                            pathItem.get = null;
                            break;
                        case "put":
                            pathItem.put = null;
                            break;
                        case "post":
                            pathItem.post = null;
                            break;
                        case "delete":
                            pathItem.delete = null;
                            break;
                        case "options":
                            pathItem.options = null;
                            break;
                        case "head":
                            pathItem.head = null;
                            break;
                        case "patch":
                            pathItem.patch = null;
                            break;
                    }
                    if (pathItem.get == null &&
                        pathItem.put == null &&
                        pathItem.post == null &&
                        pathItem.delete == null &&
                        pathItem.options == null &&
                        pathItem.head == null &&
                        pathItem.patch == null)
                    {
                        swaggerDoc.paths.Remove(key);
                    }
                }
            }

            swaggerDoc.paths = swaggerDoc.paths.Count == 0 ? null : swaggerDoc.paths;
            swaggerDoc.definitions = swaggerDoc.paths == null ? null : swaggerDoc.definitions;
        }
    }

My WebApiConfig now looks like this. I removed my ApiKeyFilter because it is not needed anymore.

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        //config.Filters.Add(new ApiKeyFilter());

        config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());
    }
}

SwaggerConfig

public class SwaggerConfig
{
    public static void Register()
    {
        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "SwashbuckleExample");
                c.DocumentFilter<AuthorizeRoleFilter>();
            })
            .EnableSwaggerUi(c => { });
    }
}



Additional

In my project I used a CustomProvider which cache the SwaggerDocument per api_key.

 public class CachingSwaggerProvider : ISwaggerProvider
    {
        private static ConcurrentDictionary<string, SwaggerDocument> _cache =
            new ConcurrentDictionary<string, SwaggerDocument>();

        private readonly ISwaggerProvider _swaggerProvider;

        public CachingSwaggerProvider(ISwaggerProvider swaggerProvider)
        {
            _swaggerProvider = swaggerProvider;
        }

        public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
        {
            HttpContext httpContext = HttpContext.Current;
            string name = httpContext.User.Identity.Name;
            var cacheKey = string.Format("{0}_{1}_{2}", rootUrl, apiVersion, name);
            return _cache.GetOrAdd(cacheKey, (key) => _swaggerProvider.GetSwagger(rootUrl, apiVersion));
        }
    }
1
  • I have implemented it as above but unfortunately not working for me can you please guide me. I am passing the api_key and value in url Jan 8, 2021 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.