当服务受 API 密钥保护时如何使 Swagger/Postman 插件工作

How to make the Swagger/Postman Plugins work when the service is protected by an API Key

在我的 ServiceStack Web 服务中,我有一个全局请求过滤器,它检查 headers 是否存在 API 键(X-FooKey),此检查阻止加载Swagger/Postman UI。我通过检查 dto 类型并将其与 Postman 的 dto 进行比较,为 Postman 创建了一个可怕的 hack,再次,不是很健壮。另一方面,Swagger 是一团糟,我真的不想模仿我对 Postman 所做的事情,所以我愿意接受建议。

最终我希望这两个插件都能够自动提供密钥,但这很可能需要 PR,考虑到我的时间限制,这是不现实的。

谢谢, 斯蒂芬

在我们当前的项目中,我们遇到了同样的问题。我们正在为 servicestack 使用 swagger 插件,并且有一个自定义请求 header 用于 API 键。 我们通过编辑 swagger-ui/index.html 轻松解决了这个问题。缺点是你不能让文件被 nuget 更新,或者手动合并。

使用 api 键的附加输入扩展 html 表单

<form id='api_selector'>
    <div id="login-logout">
        <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text" /></div>
        <div class='input'><input placeholder="username" id="input_username" name="username" type="text" /></div>
        <div class='input'><input placeholder="password" id="input_password" name="password" type="password" /></div>
        <div class='input'><a id="login" href="#">Login</a></div>
    </div>
</form>

在 javascript 件中更改 apiKeyName:

window.swaggerUi = new SwaggerUi({
    apiKey: "",
    apiKeyName: "x-fookey"
});

然后编辑登录函数:

$('#login').on('click', function (event) {
    event.preventDefault();

    var apiKey = $('#input_apiKey').val();
    var username = $('#input_username').val();
    var password = $('#input_password').val();

    $.ajax({
        url: '../api/auth/credentials',
        type: 'POST',
        data: {
            UserName: username,
            Password: password
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-FooKey', apiKey);
        }
    });
});

在我们的 API 中,我们只需要登录请求中的 api 键 header。 要将其添加到每个请求中,请参阅此 SO 问题:How to get Swagger to send API key as a http instead of in the URL