fligant
fligant

Reputation: 732

allow anonymous access if request from the specific URL or the same site asp.net core 3

I have web APIs hosted in a web application and consumed by the same site frontend by ajax requests. I need to allow anonymous access to these APIs if the request from the same web application frontend APIs host in, but if the request from an external requester its must be authorized. I use identity server 4 Bearer to secure the APIs and asp.net core 3.

Upvotes: 1

Views: 1398

Answers (1)

Aviad P.
Aviad P.

Reputation: 32639

You have to do two things:

  1. Add the default (non-whitelisted) authentication as usual
  2. Add a custom authorization policy that check the client IP

I assume you got number 1 covered. Here's how you handle number 2:

Add an authorization policy, and make it the default:

services.AddAuthorization(options =>
{
    options.AddPolicy("AllowedIpPolicy", config => 
    {
        config.AddRequirements(new AllowedIpRequirement());
    });
    options.DefaultPolicy = options.GetPolicy("AllowedIpPolicy");
});

Add an authorization requirement AllowedIpRequirement, which is just an empty class:

public class AllowedIpRequirement : IAuthorizationRequirement { }

Create a handler for this requirement:

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...
    }
}

And finally register the handler and the required IHttpContextAccessor service:

services.AddSingleton<IAuthorizationHandler, AllowedIpRequirementHandler>();
services.AddHttpContextAccessor();

Upvotes: 3

Related Questions