Swagger/Swashbuckle:具有资源所有者密码凭证授予的 OAuth2

Swagger/Swashbuckle: OAuth2 with Resource Owner Password Credentials Grant

我正在尝试将 Swashbuckle 5.0.x 与 OAuth2 结合使用。我想使用 OAuth2 的资源所有者密码凭证授予。我基本上只想先请求一个令牌,然后在每个请求中包含这个令牌(例如不需要范围)。

有人可以帮忙吗?我必须如何配置 swagger/swashbuckle?

好的,我是这样解决的:

向 swagger 添加 JavaScript 完成处理程序:

config
    .EnableSwagger(c => {
                    //do stuff
    })
    .EnableSwaggerUi(c => {
        c.InjectJavaScript(typeof(Startup).Assembly, "MyNamespace.SwaggerExtensions.onComplete.js");
    });

从 API_KEY 文本框中取 username:password:

$('#input_apiKey').change(function () {
    var key = $('#input_apiKey')[0].value;
    var credentials = key.split(':'); //username:password expected
    $.ajax({
        url: "myURL",
        type: "post",
        contenttype: 'x-www-form-urlencoded',
        data: "grant_type=password&username=" + credentials[0] + "&password=" + credentials[1],
        success: function (response) {
            var bearerToken = 'Bearer ' + response.access_token;
            window.authorizations.add('key', new ApiKeyAuthorization('Authorization', bearerToken, 'header'));
        },
        error: function (xhr, ajaxoptions, thrownerror) {
            alert("Login failed!");
        }
    });
});

谢谢@Dunken。你的回答几乎解决了我的问题,但为了让它与最新的 Swashbuckle 版本一起工作,我不得不像这样

稍微改变一下
$('#explore').off();

$('#explore').click(function () {
   var key = $('#input_apiKey')[0].value;
   var credentials = key.split(':'); //username:password expected

$.ajax({
    url: "yourAuthEndpoint",
    type: "post",
    contenttype: 'x-www-form-urlencoded',
    data: "grant_type=password&username=" + credentials[0] + "&password=" + credentials[1],
    success: function (response) {
        var bearerToken = 'Bearer ' + response.access_token;

        window.swaggerUi.api.clientAuthorizations.add('Authorization', new SwaggerClient.ApiKeyAuthorization('Authorization', bearerToken, 'header'));
        window.swaggerUi.api.clientAuthorizations.remove("api_key");
        alert("Login successfull");
       },
       error: function (xhr, ajaxoptions, thrownerror) {
        alert("Login failed!");
       }
    });
});

我有一个问题,解决方案 .InjectJavaScript() 解决了我的问题,不同之处在于我有一个自定义授权类型,因为 swagger-ui-min.js 的基本代码有授权 password 为流程 password 硬编码,解决方案是覆盖他们的代码:

$(function () {


window.SwaggerUi.Views.AuthView = Backbone.View.extend({
    events: (...),
    tpls: (...),
    selectors: {
        innerEl: ".auth_inner",
        authBtn: ".auth_submit__button"
    },
    initialize: function (e)(...),
    render: function ()(...),
    authorizeClick: function (e)(...),
    authorize: function ()(...),
    logoutClick: function (e)(...),
    handleOauth2Login: function (e)(...),
    clientCredentialsFlow: function (e, t, n)(...),
    passwordFlow: function (e, t, n) {
        this.accessTokenRequest(e, t, n, "mygrant", {
            username: t.username,
            password: t.password
        })
    },
    accessTokenRequest: function (e, t, n, r, i) {
        i = $.extend({}, {
            scope: e.join(" "),
            grant_type: r
        }, i);
        var a = {};
        switch (t.clientAuthenticationType) {
            case "basic":
                a.Authorization = "Basic " + btoa(t.clientId + ":" + t.clientSecret);
                break;
            case "request-body":
                i.client_id = t.clientId,
                    i.client_secret = t.clientSecret
        }
        $.ajax(...)
    }
});
});

(...) 具有我从 swagger-ui-min.js.

复制的原始代码

@rui-estreito 和@prime-z 的类似答案,但是当 'exploring' 第一次 API 时会提示输入用户名和密码。

1 swagger.config

c.InjectJavaScript(thisAssembly, "<project namespace>.CustomContent.apikey.js")

2 创建 \\CustomContent\apikey.js

    (function () {
    $(function () {
        console.log("loaded custom auth");
        $('#input_apiKey').off();
        $('#explore').off();
        $('#explore').click(function () {
            var credentials_un = prompt("Username");
            var credentials_password = prompt("Password");
            var client_id = $('#input_apiKey')[0].value;

            $.ajax({
                url: document.location.origin + "/token",
                type: "post",
                contenttype: 'x-www-form-urlencoded',
                data: "grant_type=password&username=" + credentials_un + "&password=" + credentials_password + "&client_id=" + client_id,
                success: function (response) {
                    var bearerToken = 'Bearer ' + response.access_token;
                    window.swaggerUi.api.clientAuthorizations.add('Authorization', new SwaggerClient.ApiKeyAuthorization('Authorization', bearerToken, 'header'));
                    alert("Login successfull");
                },
                error: function (xhr, ajaxoptions, thrownerror) {
                    alert("Login failed!");
                }
            });
        });
        /*
        */
    });
})();

3 修改apikey.js 文件属性

BuildAction 更改为 'Embedded Resource'