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


i have documented api using swashbuckle.aspnetcore.swagger , want test resources have authorize attribute on them using swagger ui.

api

 using microsoft.aspnetcore.authorization;     using microsoft.aspnetcore.mvc;     using system.linq;      namespace api.controllers     {         [route("[controller]")]         [authorize]         public class identitycontroller : controllerbase         {             [httpget]             public iactionresult get()             {                 return new jsonresult(from c in user.claims select new { c.type, c.value });             }         }     } 

swagger ui

response code unauthorized 401, how can authorize using swagger?

i have authorization server setup using identityserver4.

authorization server - startup.cs

services.addidentityserver()         .addtemporarysigningcredential()         .addinmemorypersistedgrants()         .addinmemoryidentityresources(config.getidentityresources())         .addinmemoryapiresources(config.getapiresources())         .addinmemoryclients(config.getclients())         .addaspnetidentity<applicationuser>(); 

authorization server - config.cs

    public class config {     // scopes define resources in 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

// method gets called runtime. use method configure http request pipeline.     public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory,         ecommercedbcontext context)     {         loggerfactory.addconsole(configuration.getsection("logging"));         loggerfactory.adddebug();          app.useidentityserverauthentication(new identityserverauthenticationoptions         {             authority = "http://localhost:5000/",             requirehttpsmetadata = false,             automaticauthenticate = true,             apiname = "api1"         });           // enable middleware serve generated swagger json endpoint.         app.useswagger();          // enable middleware serve swagger-ui (html, js, css etc.), specifying swagger json endpoint.         app.useswaggerui(c =>         {             c.swaggerendpoint("/swagger/v1/swagger.json", "my api v1");         });          dbinitialiser.init(context);          app.usemvc();     } 

i want authorize button redirects login screen , grants access api resources user has permissions for. possible use asp.net core 1.1 swagger middleware this? or need write javascript gets token identityserver4 authorization server? please new authentication , authorization

i solved adding new client identityserver4 authorization server project.

config.cs

 // clients want access resources (aka scopes)         public static ienumerable<client> getclients()         {             // client credentials client             return new list<client>             {                 new client                 {                     clientid="swaggerui",                     clientname = "swagger ui",                     allowedgranttypes=granttypes.implicit,                     allowaccesstokensviabrowser=true,                     redirecturis = { "http://localhost:49831/swagger/o2c.html" },                     postlogoutredirecturis={ "http://localhost:49831/swagger/" },                     allowedscopes = {"api1"}                 },     ...     ...     ...    } } 

i created swagger operationfilter in tha api red exclamation mark icon appears next method requires authorization

internal class authorizecheckoperationfilter : ioperationfilter     {         public void apply(operation operation, operationfiltercontext context)         {             // check authorize attribute             var hasauthorize = context.apidescription.controllerattributes().oftype<authorizeattribute>().any() ||                                context.apidescription.actionattributes().oftype<authorizeattribute>().any();              if (hasauthorize)             {                 operation.responses.add("401", new response { description = "unauthorized" });                 operation.responses.add("403", new response { description = "forbidden" });                  operation.security = new list<idictionary<string, ienumerable<string>>>();                 operation.security.add(new dictionary<string, ienumerable<string>>             {                 { "oauth2", new [] { "api1" } }             });             }         }     } 

to finish configured authorization in swagger adding oauth2 security definition , operationfilter

startup.cs

 services.addswaggergen(c =>             {                 c.swaggerdoc("v1", new info                 {                     version = "v1",                     title = "ecommerce api",                     description = "",                     termsofservice = "none",                     contact = new contact { name = "", email = "", url = "" },                     license = new license { name = "", url = "" }                 });                  //set comments path swagger json , ui.                 var basepath = platformservices.default.application.applicationbasepath;                 var xmlpath = path.combine(basepath, "webapi.xml");                 c.includexmlcomments(xmlpath);                  c.operationfilter<authorizecheckoperationfilter>();                  c.addsecuritydefinition("oauth2", new oauth2scheme                 {                     type = "oauth2",                     flow = "implicit",                     authorizationurl = "http://localhost:5000/connect/authorize",                     tokenurl = "http://localhost:5000/connect/token",                     scopes = new dictionary<string, string>()                     {                         { "api1", "my api" }                     }                 });             }); 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -