Search code examples
asp.net-coreauthenticationjwt

ASP.net core authentication method based on IP address


We are in the process of developing a new API. This API will be accessible to both internal and external clients.

For the internal clients, we do not need any authentication. But for the external clients, authentication is required (based upon JWT tokens).

So, eventually, we would like something like this pseudo code:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            if (HttpContext.RemoteIP.IP != "192.168.1.1") // <== something like this
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                    .AddJwtBearer(options =>
                        {
                            options.Authority = "https://Issuer.localdomain.local";
                            options.Audience = "TestAudience";
                        });
            }
                    
        }

Obviously, the line if (HttpContext.RemoteIP.IP != "192.1698.1.1") isn't going to work. But I hope that it clarifies what we're trying to do here.


Solution

  • I think you confuse "authentication" and "authorization". That's two different processes. "Authentication" means that the system confirms that you are the one that you claim to be. "Authorization" is when the system decides whether you're allowed to access the resource based on your credentials.

    The "authentication" process, in general, can't be IP-based, since the result of it should be the list of "claims": the name of the user, roles, authority, and other properties. "Authorization" on the other hand can. You can just basically say "everyone who comes from that IP is authorized to access this resource without authentication".

    To do it you basically need to setup the default authorization policy (by calling services.AddAuthorization()) with two requirement combined with OR. There are many examples of how to do it, e.g. ASP.NET Core Authorization: Combining OR requirements