授权ASP.NET Core中的本地主机

问题描述 投票:0回答:2

我是ASP.NET Core的新手,并且我有一个控制器,我只需要在我的机器上对其进行授权即可,但是出于测试目的,请拒绝其他...

我有以下配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddMvc().AddJsonOptions(options =>
    {
        options.SerializerSettings.DateFormatString= "yyyy-MM-ddTHH:mm:ssZ";
    });
    services.AddAuthentication("Cookie")
        .AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>("Cookie", null);
    services.AddLogging(builder => { builder.AddSerilog(dispose: true); });

并且在测试控制下,我启用了[Authorise] attrubute

[Authorize]
public class OrderController : Controller

是否有一种方法可以让我的本地计算机自动访问控制器的操作?类似于[Authorize(Allow=localhost)]

asp.net-core asp.net-core-2.2
2个回答
1
投票

您可以创建一个动作过滤器,如下所示:

public class LocalhostAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var ip = context.HttpContext.Connection.RemoteIpAddress;
        if (!IPAddress.IsLoopback(ip)) {
            context.Result = new UnauthorizedResult();
            return;
        }
        base.OnActionExecuting(context);
    }
}

然后使用标签Localhost

//[Authorize]
[Localhost]
public class OrderController : Controller

我相信这会起作用,限制对执行它的机器的访问。


0
投票

这比授权更白名单。授权是指检查用户是否有权执行某项操作。为此,必须首先标识用户,即对其进行身份验证。

文档中的文章Client IP Safelist显示了如何通过中间件,操作过滤器或Razor页面过滤器实现IP安全列表。

应用程序范围内的中间件

中间件选项适用于整个应用程序。该示例代码检索请求的端点IP,将其与安全ID列表进行比较,并仅在来自“安全”列表的情况下才允许进行呼叫。否则,它将返回预定的错误代码,在这种情况下为401:

public async Task Invoke(HttpContext context)
{
    if (context.Request.Method != "GET")
    {
        var remoteIp = context.Connection.RemoteIpAddress;
        _logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);

        string[] ip = _adminSafeList.Split(';');

        var bytes = remoteIp.GetAddressBytes();
        var badIp = true;
        foreach (var address in ip)
        {
            var testIp = IPAddress.Parse(address);
            if(testIp.GetAddressBytes().SequenceEqual(bytes))
            {
                badIp = false;
                break;
            }
        }

        if(badIp)
        {
            _logger.LogInformation(
                "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
            context.Response.StatusCode = 401;
            return;
        }
    }

    await _next.Invoke(context);
}

本文显示在UseMvc()之前注册它,这意味着该请求将在到达MVC中间件之前被拒绝:

app.UseMiddleware<AdminSafeListMiddleware>(Configuration["AdminSafeList"]);
app.UseMvc();

这样,我们就不会浪费CPU时间来路由和处理无论如何都会被拒绝的请求。中间件选项也是实现black列表的好选择。

动作过滤器

过滤代码本质上是相同的,这次是在从ActionFilterAttribute派生的类中定义的。筛选器定义为范围服务:

services.AddScoped<ClientIpCheckFilter>();

services.AddMvc(options =>
{
    options.Filters.Add
        (new ClientIpCheckPageFilter
            (_loggerFactory, Configuration));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

在这种情况下,请求将在被接受或拒绝之前到达MVC基础结构。

剃刀纸过滤器

代码再次相同,这次来自IPageFilter

© www.soinside.com 2019 - 2024. All rights reserved.