I am developing web api in ASP.NET Core MVC. I wonder if there is a way to make authorization token in swagger persistent, so that the authorization does not need to be done manually every time the application is run. It would make testing easier.
Asked
Active
Viewed 3,116 times
5
-
Check my answer on a similar question https://stackoverflow.com/a/69254262/11301126 – yousif Sep 20 '21 at 12:26
3 Answers
2
You can use the persistAuthorization
configuration parameter, which defaults to false
.
In .Net, set the app.UseSwaggerUI
EnablePersistAuthorization
option:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
c.EnablePersistAuthorization();
});
In the official Docker image, this can be set using PERSIST_AUTHORIZATION
.
See the Swagger UI Configuration Docs and the Pull Request.

Dan Bowling
- 1,205
- 1
- 15
- 41

vanenshi
- 65
- 2
- 11
1
The local storage can be used for keeping the authorization token.
To store the token into the local storage, type into the browser console:
localStorage.setItem('authKey', 'the authorization token')
Then, use request interceptor to supply the token from the local storage as Authorization header:
const ui = SwaggerUIBundle({
url: "/swagger/v2/swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
requestInterceptor: function (req) {
var key = localStorage.getItem("authKey");
if (key && key.trim() !== "") {
req.headers.Authorization = 'Bearer ' + key;
console.log('Authorized from authKey');
}
},
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
})
window.ui = ui;

Martin Staufcik
- 8,295
- 4
- 44
- 63
-
-
-
Related - https://github.com/scottie1984/swagger-ui-express/issues/44#issuecomment-605088470 – Wayne Bloss Mar 27 '20 at 21:35
1
If you use .NET CORE Swashbuckle, you could do the following steps to persist authorization data.
- Create an index.html for customizing SWAGGER UI configuration. An index.html should base on the default version
- Open index.html file you just created above, adding one line
configObject.persistAuthorization = true;
to persistAuthorization in window.onload event

Ngoc Huy
- 11
- 1
- 1
-
This answer applies to any Swagger UI, not just Swashbuckle. If you are using .NET Core and Swashbuckle you can configure directly in the UseSwaggerUI options, see the answer by @vanenshi – Dan Bowling May 12 '23 at 23:58