我正在尝试向我的一家公司实施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错误,声明"此请求已拒绝授权。"
我可以看到我的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 config:
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"
}
答案 0 :(得分:0)
使用.NET Core时(但似乎该问题是针对.NET Framework的),我也遇到了同样的问题。通过确保在Startup的Configure方法中您在UseAuthorization之前具有UseAuthentication来解决了该问题
(来源https://docs.microsoft.com/en-us/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.1)