Swashbuckle.AspNetCore v1.0.0 with OAuth2, flow :

2019-03-14 09:28发布

问题:

I can't seem to make my .net core web API work with swashbuckle, OAuth2 with an application flow. When I click the Authorize button, Fiddler shows that the call is OK and my local IdentityServer(4) replies with an access_token. That's all great and all but I don't think Swagger picks this up, there's nothing happening and I can't trigger my controller methods without getting a 401. I see no cookies, nothing. I'm sure I'm missing something super trivial. Can someone help me out?

Relevant code :

ConfigureServices in Startup.cs

c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{                    
    Type = "oauth2",
    Flow = "application",                      
    TokenUrl = "http://localhost:61798/connect/token",
    Scopes = new Dictionary<string, string>
    {
        { "readAccess", "Access read operations" },
        { "writeAccess", "Access write operations" }
    }
});

Configure in Startup.cs

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:61798",
    RequireHttpsMetadata = false,
    ApiName = "api1",
    AutomaticAuthenticate = true, //Doesn't change anything...
});

....

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
    c.ConfigureOAuth2("Swagger", "swaggersecret", "swaggerrealm", "Swagger UI");                
});

My IdentityServer is configured OK. I can call this API in Postman and a simple client without any problem. My only problem is Swagger (Swashbuckle.AspNetCore 1.0.0).

回答1:

We have a very similar setup for a current project. Our rest api is secured with jwt bearer authentication and azure ad b2c. In this case there is no way swagger to pick up automatically the token.

This solution works perfect for us: https://stackoverflow.com/a/39759152/536196

services.AddSwaggerGen(c =>
{
    c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});

After that when you run your swagger UI, you should see an additional field for the token.