9

Is there any method to hardcode tokens into Swagger UI permanently in Local computer or Dev Environment ?

We are testing Net Core Apis and also running them through Angular 8: developing, rebuilding, writing code, testing Swagger APIs over 100 times a day each. Looking for way, to store token below, so don't have to keep Reentering. Can be very cumbersome, consuming time, as minutes add up.

Maybe we can read a token from external file in developer desktop. Token stays so even after computer restarts, developers are not required to reenter tokens. Perhaps in appsettings.json or any file?

Or anyway to inject code with Net Core Visual Studio Environment, that does not expose token in Source control?

Answer should run all Swagger UI and APIs ran from Angular environment,

Only in QA and Production will require entry of token

enter image description here

Using Angular and Net Core 2.0 C#,

  • 1
    instead of doing it in the code you can use browser based automation tool like Selenium to insert the token. – shobhonk Jan 02 '20 at 23:46
  • well we are not using Selenium, developers are manually rebuilding and writing code, rerunning api's on their desktop, @shobhonk –  Jan 02 '20 at 23:47
  • 3
    For what I do at work when I am developing .net core or asp .net services, I use postman application. I have the tokens as global variable and test from there. It save me time to enter the token everytime in swagger which i think is unnecessary if you are going to test 100+ time a day. Postman also persists the token until you need to change it. you can also automated that process if required – shobhonk Jan 02 '20 at 23:51
  • if postman saves the token after reboot computer, that would help, also looking for swagger solution, our customer clients prefer swagger for whatever reason, –  Jan 02 '20 at 23:57
  • 1
    yes postman persists saved or updated variables. I also understand asking clients to use postman might be big ask for clients if they are not already using it. But it is the world of engineering use path of least resistance when possible rather than trying to find a solution that that may become problematic something that may not be known to other (support or otherwise). But this is only my opinion. I will dig around to see if it possible from code – shobhonk Jan 03 '20 at 00:03
  • Some APIs I saw they just post a DEMO KEY on the page so anyone can use. Of course, the DEMO KEY has a limited number of calls a day. – Ray Cheng Jan 03 '20 at 00:10
  • hi @RayCheng these are internal company APIs, what are Demo keys? –  Jan 03 '20 at 00:27
  • Check my answer to a similar question https://stackoverflow.com/a/74520311/8801767 – vanenshi Jun 04 '23 at 17:23

3 Answers3

13

I managed to do it in ASP.NET Core 5 by adding this line to startup.cs, Configure method

        app.UseSwaggerUI(c =>
        {
            c.ConfigObject.AdditionalItems.Add("persistAuthorization","true");
        });

I found this by reading this docs And here

yousif
  • 532
  • 5
  • 13
2

you add this functionality through swashbuckle

https://cpratt.co/customizing-swagger-ui-in-asp-net-core/

Enable bearer token in Swashbuckle (Swagger document)

divyang4481
  • 1,584
  • 16
  • 32
  • I will need code example, and explicit answer, reading your links, thanks –  Jan 06 '20 at 16:34
  • https://stackoverflow.com/questions/38784537/use-jwt-authorization-bearer-in-swagger-in-asp-net-core/47709074#47709074 – divyang4481 Jan 06 '20 at 17:03
  • using net core 2 –  Jan 06 '20 at 20:14
  • you can refer this list there it has explain step by step https://stackoverflow.com/questions/39009758/enable-bearer-token-in-swashbuckle-swagger-document – divyang4481 Jan 10 '20 at 12:10
  • I cannot run the command c.InjectJavascript in Net Core 2, how would I fix this?, SwaggerGenOptions does not contain definition for InjectJavascript –  Jan 13 '20 at 23:53
  • well need way to store tokens after a computer restart or browser refresh –  Jan 14 '20 at 00:07
2

Adapting my other answer to your case, your setup can look like follows:

wwwroot/swashbuckle.html

    <!-- your standard HTML here, nothing special -->
    <script>
        // some boilerplate initialisation
        // Begin Swagger UI call region
        configObject.onComplete = () => {
                // this is the important bit, see documentation
                ui.preauthorizeApiKey('api key', 'HARDCODE YOUR KEY HERE' );// key name must match the one you defined in AddSecurityDefinition method in Startup.cs
        }
        const ui = SwaggerUIBundle(configObject);
        window.ui = ui        
    }
    </script>

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            .........
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
                c.AddSecurityDefinition("api key", new ApiKeyScheme() // key name must match the one you supply to preauthorizeApiKey call in JS
                {
                    Description = "Authorization query string expects API key",
                    In = "query",
                    Name = "authorization",
                    Type = "apiKey"
                });

                var requirements = new Dictionary<string, IEnumerable<string>> {
                    { "api key", new List<string>().AsEnumerable() }
                };
                c.AddSecurityRequirement(requirements);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                if (env.IsDevelopment()) // override swashbuckle index page only if in development env
                {
                    c.IndexStream = () => File.OpenRead("wwwroot/swashbuckle.html"); // this is the important bit. see documentation https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md
                }                
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); // very standard Swashbuckle init
            });

            app.UseMvc();
        }

There are different ways to deliver your key to swagger, hard-coding might be not the best, but it should hopefully get you started. Since you indicate you only want this functionality for development environment I opted to only serve the modified file if (env.IsDevelopment()), which you, again, can tweak to your needs

timur
  • 14,239
  • 2
  • 11
  • 32
  • gave points and accepted answer, feel free to thumbs up question –  Jan 13 '20 at 21:55
  • quick question, whats the work effort generally to add this into a project? I need to give estimate to manager, 5 hours or less? 10 hours? thinking it will be 2-3 hours most –  Jan 13 '20 at 23:36
  • this is fairly simple once you know where to put it, isn't it? – timur Jan 13 '20 at 23:41
  • this is good answer, rather not change source code, is there a javascript way to save token in browser chrome console? –  Jan 14 '20 at 00:21
  • Not sure I understand the problem statement. So you just want to print it out? If you instead want to pass it in dynamically, check out the answer I refere to: it's got the code for URL parameter – timur Jan 14 '20 at 00:55