我的web API托管在web应用程序中,由相同的站点前端使用ajax请求。如果来自同一个web应用程序前端API的请求承载在其中,但如果来自外部请求者的请求必须得到授权,我需要允许匿名访问这些API。我使用标识服务器4 Bearer来保护API和asp.net核心3。
发布于 2020-09-12 00:50:29
你必须做两件事:
。
我想你已经得到第一名了。下面是你如何处理第二个问题:
添加授权策略,并使其成为默认的:
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();
https://stackoverflow.com/questions/63818580
复制