12

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

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

4

4 回答 4

15

谢谢@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!");
       }
    });
});
于 2015-07-30T14:31:07.933 回答
11

好的,我这样解决了:

为 swagger 添加一个 JavaScript 完成处理程序:

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

从 API_KEY 文本框中获取用户名:密码:

$('#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!");
        }
    });
});
于 2015-05-07T08:56:16.840 回答
0

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

$(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 复制的原始代码。

于 2018-03-15T11:30:38.730 回答
0

与@rui-estreito 和@prime-z 的答案类似,但在第一次“探索”API 时会提示输入用户名和密码。

1 招摇。配置

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 更改为“嵌入式资源”

于 2019-03-12T09:07:30.423 回答