首页 > 解决方案 > 如果来自特定 URL 或同一站点 asp.net core 3 的请求,则允许匿名访问

问题描述

我将 Web API 托管在 Web 应用程序中,并通过 ajax 请求由同一站点前端使用。如果来自同一 Web 应用程序前端 API 的请求托管在其中,我需要允许匿名访问这些 API,但如果来自外部请求者的请求必须经过授权。我使用身份服务器 4 Bearer 来保护 API 和 asp.net core 3。

标签: asp.net-coreidentityserver4webapi

解决方案


你必须做两件事:

  1. 像往常一样添加默认(非白名单)身份验证
  2. 添加检查客户端 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();

推荐阅读