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

2023-09-07 13:49:14 作者:寻你千百度、日出到迟暮

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

I'm trying to use Swashbuckle 5.0.x with OAuth2. I want to use OAuth2's Resource Owner Password Credentials Grant. I basically only want to ask for a token first and include this token in each request (e.g. no need for scopes).

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

Can anyone help with this? How do I have to configure swagger/swashbuckle?

推荐答案

好的,我是这样解决的:

OK, I solved it like this:

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

Add a JavaScript completion-handler to swagger:

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

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

Take username:password from the API_KEY textbox:

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