我已经创建了一个新的Web Api项目,添加了Asp。Net Identity和配置的OAuth如下:
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
这一切都很好,我可以调用/Token端点并获得承载令牌。
问题是,我认为这在Swagger中是无法发现的,因为它不在控制器上,因此没有为它生成xml文档。
有人知道在我的Swagger文档中显示这个登录端点的方法吗?
谢谢。
此外,我应该说,Swagger文档与我所有的控制器工作,只是,我错过了这一个明显的方法-如何登录。
ApiExplorer不会自动为您的端点生成任何信息,因此您需要添加自定义DocumentFilter以便手动描述令牌端点。
有一个这样的例子:https://github.com/domaindrivendev/Swashbuckle/issues/332:
class AuthTokenOperation : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths.Add("/auth/token", new PathItem
{
post = new Operation
{
tags = new List<string> { "Auth" },
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter> {
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "username",
required = false,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = false,
@in = "formData"
}
}
}
});
}
}
httpConfig.EnableSwagger(c =>
{
c.DocumentFilter<AuthTokenOperation>();
});
如果有人想知道如何为这个操作添加响应体,这里是更新的Ruaidhri的代码:
class AuthTokenOperation : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths.Add("/token", new PathItem
{
post = new Operation
{
tags = new List<string> { "Auth" },
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter> {
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData"
},
new Parameter
{
type = "string",
name = "username",
required = false,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = false,
@in = "formData"
}
},
responses = new Dictionary<string, Response>()
{
{
"200",
new Response {schema = schemaRegistry.GetOrRegister(typeof(OAuthTokenResponse))}
}
}
}
});
}
}
class OAuthTokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public long ExpiresIn { get; set; }
[JsonProperty("userName")]
public string Username { get; set; }
[JsonProperty(".issued")]
public DateTime Issued { get; set; }
[JsonProperty(".expires")]
public DateTime Expires { get; set; }
}