【发布时间】:2021-07-27 21:31:48
【问题描述】:
在向我的应用程序添加新的承载身份验证时遇到一些困难,我无法弄清楚,我需要的一段代码导致我的端点返回 404 错误,但删除后我成功了能够在没有 404 错误的情况下到达端点,见下文。
首先,我的应用程序既充当身份服务器,又充当接受不记名令牌的 API。
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://www.example.com/";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "openid");
});
});
// THIS IS THE CODE CAUSING THE 404 ERROR
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<DevContext>();
从上面看,如果我尝试到达使用 [Authorize] 装饰的控制器端点,则会收到 404 响应。如果我注释掉最后几行(参见代码中的注释),那么我就可以成功到达我的端点。
为什么会收到 404 错误?我认为这一定是因为 .AddIdentity 覆盖了 Bearer 身份验证,并且因为我的控制器装饰有 [Authorize] 我无法访问它?
我的应用程序不能同时作为 API 和身份服务器吗?
这是我在未注释有问题的代码时在输出日志中看到的内容(404 响应):
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 GET https://localhost:44310/api
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed.
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: Information: AuthenticationScheme: Identity.Application was challenged.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 13.422ms 302
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 GET https://localhost:44310/Account/Login?ReturnUrl=%2Fapi
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 2.0776ms 404
这是我在注释有问题的代码时看到的(成功响应):
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 GET https://localhost:44310/api
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: Successfully validated the token.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization was successful.
【问题讨论】:
-
拨打
AddIdentity的电话高于AddAuthentication的电话,它应该可以工作。 -
@KirkLarkin 不幸的是,这似乎没有什么不同——即使 AddAuthentication 低于对 AddIdentity 的调用,我仍然会收到 404 错误。我在上面的原始帖子中添加了一些输出日志,希望这些日志能够更清楚地了解发生了什么?
-
见stackoverflow.com/a/52207398/2630078,我在这里解释了这里发生的事情以及如何解决它。
-
@KirkLarkin 谢谢!这正是我所需要的。我整天都在做这个,非常感谢!
-
很高兴能帮上忙。我将此标记为重复,因此它与帮助您的答案相关联。
标签: asp.net-core identity