Create a gist now

Instantly share code, notes, and snippets.

Using Swagger for Implicit Grant on ADFS 4.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Swashbuckle;
using Swashbuckle.Swagger;
using System.Web.Http.Description;
namespace TodoListService
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 ( == null) = new List<IDictionary<string, IEnumerable<string>>>();
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{"oauth2", new List<string> {"sampleapi", "user_impersonation"}}
// NOTE: You must also configure 'EnableApiKeySupport' below in the SwaggerUI section
// .Description("API Key Authentication")
// .Name("apiKey")
// .In("header");
.Description("OAuth2 Implicit Grant")
.Scopes(scopes =>
scopes.Add("user_impersonation", "use user impersonation");
scopes.Add("sampleapi", "try out the sample api");
// Set this flag to omit descriptions for any actions decorated with the Obsolete attribute
// If you've defined an OAuth2 flow as described above, you could use a custom filter
// to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required
// to execute the operation
// Post-modify the entire Swagger document by wiring up one or more Document filters.
// This gives full control to modify the final SwaggerDocument. You should have a good understanding of
// the Swagger 2.0 spec. -
// before using this option.
// If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to
// the Swagger 2.0 specification, you can enable UI support as shown below.
clientId: "7b2...7f2",
clientSecret: "4pr...wYP",
realm: "https://localhost:44326/",
appName: "Swagger UI",
//additionalQueryStringParams: new Dictionary<string, string>() { { "foo", "bar" } }
additionalQueryStringParams: new Dictionary<string, string>() { { "audience", "https://localhost:44326/NativeTodoListService1" } }
// If your API supports ApiKey, you can override the default values.