Swagger 虚张声势/虚张声势:授予资源所有者密码凭据的OAuth2

Swagger 虚张声势/虚张声势:授予资源所有者密码凭据的OAuth2,swagger,swagger-ui,swashbuckle,Swagger,Swagger Ui,Swashbuckle,我正在尝试将SwashBuck5.0.x与OAuth2一起使用。我想使用OAuth2的资源所有者密码凭据授予。我基本上只想首先请求一个令牌,并在每个请求中包含这个令牌(例如,不需要作用域) 有人能帮忙吗?如何配置swagger/Swashback?好的,我是这样解决的: 向swagger添加JavaScript完成处理程序: config .EnableSwagger(c => { //do stuff }) .EnableS

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


有人能帮忙吗?如何配置swagger/Swashback?

好的,我是这样解决的:

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

config
    .EnableSwagger(c => {
                    //do stuff
    })
    .EnableSwaggerUi(c => {
        c.InjectJavaScript(typeof(Startup).Assembly, "MyNamespace.SwaggerExtensions.onComplete.js");
    });
从API_密钥文本框中获取用户名:密码:

$('#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!");
        }
    });
});

谢谢你,邓肯。你的答案几乎解决了我的问题,但为了让它适用于最新的Swashback版本,我不得不对它进行如下更改

$('#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的基本代码具有流密码的授权密码硬编码,解决方案是覆盖他们的代码:

$(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的答案,但这会在首次“探索”API时提示输入用户名和密码

1 swagger.config 3修改apikey.js文件属性
BuildAction更改为“Embedded Resource”

您能否指定在何处添加第一个代码段“config.EnableSwagger…”?第二个是我把你添加到index.html,对吗?我在我的Startup.cs(OWIN Startup)中添加了这个。第二个是JavaScript文件(onComplete.js),这是我添加到ASP.NET Web API项目中的一个嵌入式资源。我必须发布一个新的答案,以使其适用于最新版本。这对我不起作用,我得到了令牌,但当请求命中我的API时,授权标头为空,你能发布你的招摇过市配置吗?@Derek:我不使用招摇过市配置,也不使用任何按钮。请在新帖子中分享你的代码,并让我知道。太好了!请包括最后的
})插入代码块。正在尝试执行此操作。我已在根目录中将脚本添加到我的项目中。将其标记为嵌入式资源,但当我重建并加载swagger UI时,它会说它无法对其进行优化。我的脚本是:c.InjectJavaScript(thisAssembly,“.SwaggerExtensions.SwaggerJWTScript.js”);对不起,迟了答复。检查js文件是否不仅是嵌入式资源,而且还标记为
Copy Always
。使用以下代码配置
c=>c.InjectJavaScript(typeof().Assembly,.onComplete.js”)
@prime\z这是问题的完整、正确答案。谢谢你!
c.InjectJavaScript(thisAssembly, "<project namespace>.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!");
                }
            });
        });
        /*
        */
    });
})();