9 c# swagger .net-core asp.net-core angular
有没有什么方法可以在本地计算机或开发环境中将令牌永久硬编码到 Swagger UI 中?
我们正在测试 Net Core API,并通过 Angular 8 运行它们:开发、重建、编写代码、每天测试 Swagger API 超过 100 次。想办法,把token存储在下面,这样就不用一直Reentering了。随着时间的推移,可能会非常麻烦、耗时。
也许我们可以从开发人员桌面的外部文件中读取令牌。即使计算机重新启动后,令牌仍会保留,开发人员无需重新输入令牌。也许在 appsettings.json 或任何文件中?
或者无论如何,使用 Net Core Visual Studio 环境注入代码,不会在源代码管理中公开令牌?
答案应该运行从 Angular 环境运行的所有 Swagger UI 和 API,
仅在 QA 和生产中需要输入令牌
使用 Angular 和 Net Core 2.0 C#,
小智 17
我设法在 ASP.NET Core 5 中通过将此行添加到startup.cs,配置方法来做到这一点
app.UseSwaggerUI(c =>
{
c.ConfigObject.AdditionalItems.Add("persistAuthorization","true");
});
Run Code Online (Sandbox Code Playgroud)
根据您的情况调整我的其他答案,您的设置可能如下所示:
<!-- 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>
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
有多种方法可以提供 swagger 的密钥,硬编码可能不是最好的,但它应该可以帮助您入门。由于您表明您只想在开发环境中使用此功能,因此我选择仅提供修改后的文件if (env.IsDevelopment()),您可以再次根据您的需求进行调整
| 归档时间: |
|
| 查看次数: |
6327 次 |
| 最近记录: |