asp.net-core - 如果来自特定 URL 或同一站点 asp.net core 3 的请求,则允许匿名访问
问题描述
我将 Web API 托管在 Web 应用程序中,并通过 ajax 请求由同一站点前端使用。如果来自同一 Web 应用程序前端 API 的请求托管在其中,我需要允许匿名访问这些 API,但如果来自外部请求者的请求必须经过授权。我使用身份服务器 4 Bearer 来保护 API 和 asp.net core 3。
解决方案
你必须做两件事:
- 像往常一样添加默认(非白名单)身份验证
- 添加检查客户端 IP 的自定义授权策略
我假设你得到了第一名。以下是您处理 2 号的方法:
添加授权策略,并将其设为默认值:
services.AddAuthorization(options =>
{
options.AddPolicy("AllowedIpPolicy", config =>
{
config.AddRequirements(new AllowedIpRequirement());
});
options.DefaultPolicy = options.GetPolicy("AllowedIpPolicy");
});
添加一个授权要求AllowedIpRequirement
,它只是一个空类:
public class AllowedIpRequirement : IAuthorizationRequirement { }
为此需求创建一个处理程序:
public class AllowedIpRequirementHandler : AuthorizationHandler<AllowedIpRequirement>
{
private readonly IHttpContextAccessor _contextAccessor;
public AllowedIpRequirementHandler(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AllowedIpRequirement requirement)
{
var httpContext = _contextAccessor.HttpContext;
if (IsAllowedIp(httpContext.Connection.RemoteIpAddress) ||
context.User.Identity.IsAuthenticated)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
private bool IsAllowedIp(IPAddress connectionRemoteIpAddress)
{
// ...check if allowed ip...
}
}
最后注册处理程序和所需的IHttpContextAccessor
服务:
services.AddSingleton<IAuthorizationHandler, AllowedIpRequirementHandler>();
services.AddHttpContextAccessor();
推荐阅读
- ruby-on-rails - 如何确保 ActiveStorage URL 实际过期?
- r - RasterStack 数学和条件语句的限制
- queue - 如何在 AnyLogic 中从模拟页面设置排队模式
- javascript - Javascript Unexpected token { 在 JSON 中,带有 Twig 变量
- python - 如何使用 Numpy 将多维数组附加到新维度?
- python - Flask + Gunicorn + Nginx,使用来自非根位置块的 proxy_pass 出现 404 错误
- php - 如何通过自定义分类过滤这些结果?
- regex - 正则表达式:双引号之间的数字和逗号交替
- javascript - 如何将方法从一个组件传递到另一个组件并在 Vue.js 中单击时使用它?
- java - OpenWeatherMap API:遇到 NullPointerException