如果来自特定URL或与asp.net core 3相同的站点的请求,则允许匿名访问

问题描述

我有Web API托管在Web应用程序中,并且由ajax请求由同一站点前端使用,如果来自同一Web应用程序前端API的请求位于主机中,但是如果来自外部的请求存在,则需要允许匿名访问这些API请求者必须获得授权我使用身份服务器4 Bearer来保护API和asp.net core 3。

解决方法

您必须做两件事:

  1. 像往常一样添加默认(非白名单)身份验证
  2. 添加用于检查客户端IP的自定义授权策略

我认为您已经覆盖了1号。这是处理数字2的方法:

添加授权策略,并将其设置为默认值:

extension String {
    func replacePattern(pattern: String,replaceWith: String = "") -> String {
        do {
            let regex = try NSRegularExpression(pattern: pattern,options: NSRegularExpression.Options.caseInsensitive)
            let range = NSMakeRange(0,self.count)
            return regex.stringByReplacingMatches(in: self,options: [],range: range,withTemplate: replaceWith)
        } catch {
            return self
        }
    }
    
    var fixZeroWidthSpace: String {
        addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.replacePattern(pattern: "%E2%80%8B",replaceWith: "") ?? ""
    }
}

let url = urlString.fixZeroWidthSpace 

添加一个授权要求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