【问题标题】:JWT + Swagger on Dotnet CoreDotnet Core 上的 JWT + Swagger
【发布时间】:2018-07-01 06:21:27
【问题描述】:

I'm aware that you can configure swagger to provide a UI element to place a JWT。 (结果如下):

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

如何通过代码为 Swagger 提供密钥? 有效地,预先填写以下文本框或更直接,只需自动包含一个有效 Bearer来自 Swagger UI 的每个 REST 请求的令牌标头。

【问题讨论】:

  • 也许我需要使用oAuth来松散地实现这个效果?

标签: .net-core swagger


【解决方案1】:

我们过去做过这样的事情:

 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"));
}

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2019-07-26
    • 2016-12-11
    • 1970-01-01
    • 2018-03-07
    • 2019-06-19
    • 2023-01-19
    • 2018-01-22
    相关资源
    最近更新 更多