JWT + Swagger在Dotnet Core上

时间:2018-01-22 15:09:08

标签: .net-core swagger

I'm aware that you can configure swagger to provide a UI element to place a JWT。 (导致类似以下内容):

Authorize button on Swagger UI

但是,我的偏好(用于开发)是自动生成并自动为Swagger UI Access提供JWT。我理解安全隐患。我将以其他方式处理这个问题,但我的问题很简单:

如何通过代码向Swagger提供密钥?有效地,预先填写以下文本框或更多内容,只需自动包含有效 {{1来自Swagger UI的每个REST请求的标记头。

Fill-in Target in swagger

1 个答案:

答案 0 :(得分:0)

过去我们做过类似的事情:

 config
   .EnableSwagger(c => {
                    c.SingleApiVersion("v1", 
                    ConfigurationManager.AppSettings["ServiceName"]);
                    AddXmlComments(c);
                  })
   .EnableSwaggerUi(c => c.InjectJavaScript(Assembly.GetEntryAssembly(), 
        "<<your namespace and file location>>.index.js"));

然后index.js会是这样的:

$("#input_apiKey").change(function () {
    setHeader($("#input_apiKey").val());
});

$(function () {
    var request = $.ajax({
        url: "<<url for getting your auth token>>",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
    });

    request.done(function (res) {
        setHeader(res.Header);
        $('#input_apiKey')[0].value = res.Header;
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Authorization Failed: " + textStatus);
    });

    $("#input_apiKey").attr("title", "Enter Header value from user service");
    $("#input_apiKey").attr("placeholder", "<<token header name>>");
})

function setHeader(key) {
    swaggerUi.api.clientAuthorizations.remove("api_key");
    swaggerUi.api.clientAuthorizations.remove("key");
    swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("<<token header name>>", key, "header"));
}