【发布时间】:2021-08-22 13:27:00
【问题描述】:
问题
嗨。我正在开发一个 ASP.Net 5(核心不是 MVC5)Web API。我正在使用带有外部 OpenID Connect 身份提供程序的 cookie 身份验证方案。我正在使用Authorize 属性来确保仅对经过身份验证的用户执行的操作。由于这是一个 Web API,我希望服务器在尝试访问此类操作端点而不经过身份验证时向客户端返回 401。但是,我总是被重定向到我的 OpenID Connect 提供商的登录页面。
设置
以下是相关的服务配置:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(...);
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(...)
.AddOpenIdConnect(...)
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
我的端点基本上如下所示:
FooController.cs
[ApiController]
[Route("api/[controller]")]
public class FooController : ControllerBase
{
[Authorize]
[HttpGet]
public ActionResult<int> GetBar()
{
return Ok(1);
}
}
尝试
我已尝试按照其他问题的解决方案提出建议,例如以下问题: https://stackoverflow.com/a/47987035/11800986。我在添加 cookie 身份验证时设置了这些重定向事件。
Startup.cs
.AddCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
};
})
当我在调试模式下运行服务器并在这些重定向处理程序中设置断点时,它们甚至都不会触发。这应该是因为我使用 OpenId Connect 作为默认质询方案,而不是 cookie。
为了尝试解决这个问题,我以类似的方式附加到 OpenId Connect 事件:
Startup.cs
.AddOpenIdConnect(options =>
{
options.Events.OnRedirectToIdentityProvider = context =>
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.CompletedTask;
};
});
当我用断点调试它时,这个事件确实会被命中,但它似乎根本没有停止重定向。
关于如何解决这个问题的任何想法?任何帮助将不胜感激!
【问题讨论】:
标签: asp.net authentication redirect openid-connect