我正在尝试将OAuth实施到我公司的某个项目中,但无法解决以下问题 .
我们使用 IdentityServer4
来实现我们自己的授权服务器,到目前为止工作正常 . 我想用OAuth保护的资源是一个利用 Swagger/Swashbuckle
的WebApi .
我按照 IdentityServer4 QuickStartExamples
配置服务器和本教程[使用Swagger,Swashbuckle和OAuth2安全Web API(第2部分)](http://knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-2用于配置Swagger / Swashbuckle) .
我有一个虚拟动作,它只返回一个字符串,它按预期工作 .
当我用 [Authorize]
装饰动作时,swagger-ui中出现一个小红色图标,表示我必须登录才能访问此方法 . 登录过程正常工作:我被重定向到Quickstart-UI,可以使用testuser "Bob"登录,并在成功登录后重定向到swagger-ui . 问题:成功登录后,我仍然收到401错误,说明"Authorization has been denied for this request."
我可以看到我的IdentityServer在swagger-ui中返回了一个不记名令牌,所以我猜这部分工作正常,问题似乎是招摇/ swashbuckle .
我可能还有其他任何与令牌有关的事情吗?在我到目前为止阅读的教程中,swagger配置被修改为我所做的(见下文)就是这样,所以我猜swagger / swashbuckle应该处理这个 - 但是我可能错过了什么?
SwaggerConfig.cs:
c.OAuth2("oauth2")
.Description("OAuth2 Implicit Grant")
.Flow("implicit") //also available: password, application (=client credentials?)
.AuthorizationUrl("http://localhost:5000/connect/authorize")
.TokenUrl("http://localhost:5000/connect/token")
.Scopes(scopes =>
{
scopes.Add("My.Web.Api", "THE Api");
});
// etc. .....
c.OperationFilter<AssignOAuth2SecurityRequirements>();
// etc. .....
c.EnableOAuth2Support(
clientId: "swaggerui",
clientSecret: "secret",
realm: "dummyrealm",
appName: "Swagger UI"
);
在SwaggerConfig.cs中过滤授权属性:
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
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", new [] { "My.Web.Api" } }
};
operation.security.Add(oAuthRequirements);
}
}
IdentityServer api配置:
new ApiResource("My.Web.Api", "THE Api")
IdentityServer客户端配置:
new Client
{
ClientId = "swaggerui",
ClientName = "Swagger UI",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
AllowedCorsOrigins = { "http://localhost:5858" },
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5858/swagger/ui/o2c-html" },
PostLogoutRedirectUris = { "http://localhost:5858/swagger/ui/o2c-html" },
AllowedScopes =
{
"My.Web.Api"
}
登录后重定向的屏幕截图: