我正在尝试对我公司的一个项目实施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,可以使用测试用户“ Bob”登录,并且在成功登录后被重定向到swagger-ui。问题:成功登录后,仍然出现401错误,提示“该请求的授权已被拒绝”。
[我可以看到我的IdentityServer在swagger-ui中返回了一个承载令牌,所以我猜这部分工作正常,问题似乎是swagger / 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"
}
使用.NET Core时(但似乎该问题是针对.NET Framework的,我也遇到了同样的问题。通过确保在“启动的配置方法”中具有UseAuthorization之前的UseAuthentication来解决此问题]
(源https://docs.microsoft.com/en-us/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.1)