0

Please see this StackOverflow question.

I am porting an application from .Net Framework to .Net Core 3.1. The solution in the above SO question was used in the .Net Framework solution to make sure that the controller could only be used by other applications on the same server.

I have found a similar AuthorizeAttribute, but is does not have the same method to override.

I also think I know how to add filters:

services.AddControllers(options =>
        {
            options.Filters.Add(*some_filter_here*);
        });

But I don't know how to create the filter.

How do I do this in .Net Core 3.1? Or is there a different way to do what I want?

Rena
  • 14,556
  • 3
  • 15
  • 44
Halvard
  • 3,655
  • 6
  • 33
  • 49

1 Answers1

1

You can create a custom Authorization filter:

public class LocalAuthorizationFilter : IAuthorizationFilter
{
    public LocalAuthorizationFilter()
    {
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var isLocal = context.Request.IsLocal();
        if (!isLocal)
        {
            context.Result = new ForbidResult();
        }
    }

    public static bool IsLocal(this HttpRequest req)
    {
        var connection = req.HttpContext.Connection;
        if (connection.RemoteIpAddress != null)
        {
            if (connection.LocalIpAddress != null)
            {
                return connection.RemoteIpAddress.Equals(connection.LocalIpAddress);
            } 
            else 
            {
                return IPAddress.IsLoopback(connection.RemoteIpAddress);
            }
        }
 
        // for in memory TestServer or when dealing with default connection info
        if (connection.RemoteIpAddress == null && connection.LocalIpAddress == null)
        {
            return true;
        }
 
        return false;
    }
}

There is not an IsLocal property anymore (HttpRequest documentation), so I added one in your class. You can extract it and add it in an extentions class to be used everywhere. Kudos to this guy here

Athanasios Kataras
  • 20,791
  • 3
  • 24
  • 45