S.Anaconda S.Anaconda - 1 year ago 172
C# Question

How can I setup SwashBuckle.AspNetCore.Swagger to use Authorization?

I have documented my api using Swashbuckle.AspNetCore.Swagger and I want to test some resources that have Authorize attribute on them using swagger ui.


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Api.Controllers
public class IdentityController : ControllerBase
public IActionResult Get()
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });

swagger ui

Response code is Unauthorized 401, so how can I authorize this using swagger?

I have an Authorization server setup using IdentityServer4.

authorization server - startup.cs


authorization server - config.cs

public class Config
// scopes define the resources in your system
public static IEnumerable<IdentityResource> GetIdentityResources()
return new List<IdentityResource>
new IdentityResources.OpenId(),
new IdentityResources.Profile(),

public static IEnumerable<ApiResource> GetApiResources()
return new List<ApiResource>
new ApiResource("api1", "My API")

api - startup.cs

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
ECommerceDbContext context)

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
Authority = "http://localhost:5000/",
RequireHttpsMetadata = false,
AutomaticAuthenticate = true,
ApiName = "api1"

// Enable middleware to serve generated Swagger as a JSON endpoint.

// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");



I want an authorize button which redirects to a login screen and then grants access to api resources which the user has permissions for.
Is it possible to use asp.net core 1.1 Swagger middleware to do this? Or do I need to write some javascript that gets a token from IdentityServer4 authorization server?
Please help as I am new to authentication and authorization

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download