- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将 swagger 实现到我的 Asp.Net Web API 中,但遇到了问题。
我正在使用密码资源所有者流程,并且我必须添加解决方法才能执行此操作,这在以下堆栈溢出问题中有所介绍:-
Swagger/Swashbuckle: OAuth2 with Resource Owner Password Credentials Grant
我已经一切正常,承载 token 通过 javascript 添加到当前浏览器窗口中的请求 header ,但对需要授权的 Controller 方法的 api 调用仍然返回“401 - 授权失败”。
这是获取不记名 token 并添加 header 的 JavaScript:-
$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
var credentials = key.split(':'); //username:password expected
$.ajax({
url: "http://localhost:42291/token",
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 window.SwaggerClient.ApiKeyAuthorization('Authorization', bearerToken, 'header'));
window.swaggerUi.api.clientAuthorizations.remove('api_key');
alert("Login Succesfull!");
},
error: function (xhr, ajaxoptions, thrownerror) {
alert("Login failed!");
}
});
});
Swagger 响应中的 Curl 是:-
curl -X GET --header "Accept: application/json" --header "Authorization: Bearer NqlSG-WyTx2zkYE8xFklGyZWlQDZdsCKZBHruEXvX47N7PAzw4-jZ4eH5D0yFzQTXj13RwKFFt1rUZt2fzWj1vR5UR87wdlKC3YvsTojYV4-3DsWwY7qYRfiKPuM0j09c3X5lnrtlBVJ1rBRUH0TLjfw_yGxgoLBwOJl9xyC1YWNoPOe2nzL4lMOHodAnMem0IBMJmUo3Rt575tnWAbBsQXWhlImDIxCZXvkZdJtlXfIfBSUdY9gfRWL0ZjKbf7m2-yLzH0gpMAMuKaADmJlIudJc0d4SP1Nn2Kh2HuVH8CX4QgZuu4egl9N6rY2smorP2vBSC4_dC4CpmYYzOTu2wUnUhHDY2Q6NWl377ijDKwZLcW9jtD-2tBiEGmFuRV0mVGnh0zc4w9Ao9jPCdtrbSyGitgloBW-UG2bfyao3eE" "http://localhost:42291/api/v1/claims"
我根本看不出这有什么问题。
然后,我使用 Postman 调用完全相同的 URL 调用,使用在 javascript 调用中生成的相同访问 token ...
你猜怎么着......它工作得很好。
编辑
我尝试从 Controller 中删除授权属性,以便我可以在请求到达 Controller 方法时检查请求。
查看请求 header ,Authorization 属性为 null。
不知道这是为什么。 CURL 建议将其放入请求中。
编辑2
我已经包含了我的安全定义:-
"securityDefinitions": {
"oauth2": {
"type": "oauth2",
"description": "OAuth2 Password Grant",
"flow": "password",
"tokenUrl": "http://localhost:42291/token",
"scopes": {}
}
}
编辑3当直接在命令行中通过 cURL 公开时,此 api 调用的 Swagger UI 中显示的 cURL 可以正常工作。
现在我完全困惑了。
最佳答案
我已经成功解决了这个问题。这是一个简单的类型不匹配,导致我悲伤了好几天。
在 onComplete.JS 中,我需要创建一个与 swagger 规范中提供的 key 相匹配的 key 。
如果您检查上面的代码片段,您会发现我创建了一个 key 并将其称为“授权”。但这与命名的安全定义“oauth2”不匹配。
工作代码:-
$('#input_apiKey').change(function () {
var key = $('#input_apiKey')[0].value;
var credentials = key.split(':');
$.ajax({
url: "http://localhost:42291/token",
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.remove('api_key');
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", bearerToken, "header");
window.swaggerUi.api.clientAuthorizations.add('oauth2', apiKeyAuth);
alert("Login Succesfull!");
},
error: function (xhr, ajaxoptions, thrownerror) {
alert("Login failed!");
}
});
});
为了进一步解释这一点,您需要创建 IOperationFilter 的实现,以便 swagger 可以确定 api 的哪些方法需要授权。正确配置后,您应该会在 swagger 规范中看到针对每个 api 调用的安全定义:-
我的 IOperationFilter 实现:-
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
/// <summary>
/// Apply Security Measures.
/// </summary>
/// <param name="operation"></param>
/// <param name="schemaRegistry"></param>
/// <param name="apiDescription"></param>
/// <exception cref="NotImplementedException"></exception>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
// Determine if the operation has the Authorize attribute
var authorizeAttributes = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
if (!authorizeAttributes.Any())
return;
// Initialize the operation.security property
if (operation.security == null)
operation.security = new List<IDictionary<string, IEnumerable<string>>>();
// Add the appropriate security definition to the operation
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", Enumerable.Empty<string>() }
};
operation.security.Add(oAuthRequirements);
}
}
关于asp.net-web-api2 - SwashBuckle/Swagger - OAuth 资源所有者密码流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929280/
我将 Swashbuckle.AspNetCore NuGet 添加到我的项目中,它似乎运行良好。 (我得到 Swagger 页面就好了。) 但是当我处理另一个问题(不使用 Swagger 页面)时,
.Netcore 2.2虚张声势 4.0.1 Swagger UI 在本地主机上运行,但在部署到 Azure ASE 到由应用程序网关管理的站点后,Swagger 将不会加载。 (已确认生成 sw
这是我的理解: Swagger 是一种编写文档的符号/规则。但为什么它被称为框架(如 Angular/MVC)? Swashbuckle 是一个生成文档(基于 Swagger 规则)的程序(JavaS
使用 ABP 框架 (3.3) 和 ASP.NET Core (3.1)。 在编译应用程序后,我尝试使用 Swashbuckle.AspNetCore.Cli ( https://github.com
如何在 Swashbuckle 6.0.0 的选项中禁用 Swagger Schema 验证器。我知道它在本地运行时默认关闭,但没有看到 SwaggerUI() 的 validatorURL 选项 最
我在隐藏调用时遇到 Swashbuckle 问题,链接到调用的模型定义保留在生成的 JSON 中的定义中。 使用文档过滤器,我可以从界面中删除调用。 调用保留在生成的 JSON 中,但在 Swagge
我使用 Swashbuckle 将 Swagger 文档添加到我的 ASP.NET Web API 项目中。如何在不注入(inject) CSS 的情况下从文档页面隐藏默认标题(带有 swagger
在 Swashbuckle 中,有一个名为 OrderActionGroupsBy 的设置,它应该更改 API 内的排序,但我所做的一切都不起作用,而且我无法确定这是否是 Swashbuckle 问题
我的应用程序是一个 ASP.NET Core 1.0 Web API。 我有以下 Controller : [HttpGet("{someData:MinLength(5):MaxLength
我正在尝试为 swashbuckle 注册自定义路由。但是我想不通。 我需要做的是为当前路由添加一个扩展。 举个例子:我需要将它设置为 swagger.aspx/ui 而不是 swagger/ui .
我有一个包含 90 多个表的数据库,这些表都通过外键相互交叉链接。 当我打开我的 API 的 swagger 页面时,加载需要 2 多分钟。原因似乎是它正在为每个 API 生成 Model 和 Exa
我正在使用 Swashbuckle v3.0。 我不确定这是否是一个错误,但多态性并没有像它应该的那样工作。我有以下类(class): BasePersonDocumentDto { Id,
在 ASP.NET Core webapp 中使用 Swashbuckle.AspNetCore,我们有如下响应类型: public class DateRange { [JsonConver
我正在使用 SwaggerResponse 属性来装饰我的 api Controller 操作,这一切工作正常,但是当我查看生成的文档时,参数的描述字段是空的。 是否有基于属性的方法来描述操作参数(而
我有一个 C# 对象 public class MyObject { public int property1 { get; set; } public string property2 { ge
我应该如何在 .net 核心中设置 swashbuckle 以便我可以从请求正文上传文件(多部分,表单值模型绑定(bind)已禁用)? 我尝试了什么(显然在 swashbuckle 启动配置中添加了
我从 Swashbuckle 开始,我使用 Swashbuckle 在 .NET Core 中创建了一个 Web API。 我需要在 IIS 站点的子应用程序中部署我的 API IIS 基础设施 II
是否可以在 asp.net Core 2.0 Web API 上的 Swashbuckle UI 上设置默认选中的身份验证范围复选框? 我使用“openid”范围,我希望每次都检查它。 谢谢你。 最佳
我们在代码中使用 JetBrains 注释来定义对象模型的可空性行为。默认情况下,我无法在使用 Swashbuckle.AspNetCore v5.0.0-rc5 实现的 Swagger UI 中看到
我们在代码中使用 JetBrains 注释来定义对象模型的可空性行为。默认情况下,我无法在使用 Swashbuckle.AspNetCore v5.0.0-rc5 实现的 Swagger UI 中看到
我是一名优秀的程序员,十分优秀!