🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / .Net Core Web Api / IPFilterMiddleware ip filtreleme ip engelleme sadece kendi ip me izin verme UseMiddleware kullanımı

1-) .Net 6 Core Web Api  - IPFilterMiddleware ip filtreleme ip engelleme sadece kendi ip me izin verme UseMiddleware kullanımı

 

 

1- Program.cs e bu üç satır kod eklenir

 

// ip filtreleme  ::1 127.0.0.1   -> bu iki değer localhost demek

List<string> iplerim =new List<string> { "78.163.180.32","158.55.615.55", "::1", "127.0.0.1" };

builder.Services.AddScoped<IPFilterMiddleware>(provider => new IPFilterMiddleware(iplerim));

app.UseMiddleware<IPFilterMiddleware>(); // IP filtreleme middleware'ını ekleyin

 

 

2- IPFilterMiddleware.cs kodları aşağıda

 

 

namespace NetCoreApiTokenAuth.Helpers

{

    public class IPFilterMiddleware : IMiddleware

    {

        private readonly List<string> _allowedIPs;

        public IPFilterMiddleware(List<string> allowedIPs)

        {

            _allowedIPs = allowedIPs;

        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)

        {

            // burada ip leri sql den çekebilirsin

            var ipAddress = context.Connection.RemoteIpAddress;

            if(ipAddress == null) { await next(context); }

            string ip = ipAddress.ToString();

            var varmi = _allowedIPs.Where(x=>x.Equals(ip.ToString())).FirstOrDefault();

            if (varmi==null)

            {

                context.Response.StatusCode = 403; // Erişim reddedildi

                await context.Response.WriteAsync(ip.ToString() + " ip izniniz yok !");

                return;

            }

            await next(context);

        }

    }

}

 

 

3- SQL DEN ÇEKMEK

using NetCoreApiTokenAuth.Entities;

 

namespace NetCoreApiTokenAuth.Helpers

{

    public class IPFilterMiddleware : IMiddleware

    {

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)

        {

            var ipAddress = context.Connection.RemoteIpAddress;

            if (ipAddress == null) { await next(context); }

 

            string globalip = ipAddress.ToString();

 

            using var contextDb = new Context();

            var ipvarmi = contextDb.IpYetki.Where(x=>x.aktif==true && x.ip== globalip).FirstOrDefault();

 

            if (ipvarmi==null)

            {

                context.Response.StatusCode = 403;

                await context.Response.WriteAsync(globalip + " ip izniniz yok !");

            }

 

            await next(context);

        }

    }

}

 

 2024 Ocak 05 Cuma
 281