首页 > 解决方案 > Swagger permanent authorization token

问题描述

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.

标签: asp.net-core-mvcswagger

解决方案


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;

推荐阅读