-
Notifications
You must be signed in to change notification settings - Fork 0
/
IpFilterMiddeware.cs
58 lines (53 loc) · 1.73 KB
/
IpFilterMiddeware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
namespace Salt.IpFilter;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
/// <summary>
/// IP filter Middleware
/// </summary>
public class IpFilterMiddeware
{
private readonly RequestDelegate _next;
private ILogger<IpFilterMiddeware> _logger;
private readonly IpFilterOptions _options;
/// <summary>
/// DI ctor
/// </summary>
public IpFilterMiddeware(RequestDelegate next, ILogger<IpFilterMiddeware> logger, IOptions<IpFilterOptions> options)
{
_next = next;
_logger = logger;
_options = options.Value;
}
/// <summary>
/// Basic middleware method
/// </summary>
public async Task Invoke(HttpContext context)
{
IPAddress requestIpAddress = context.Connection.RemoteIpAddress;
switch (_options.Policy)
{
case IpFilterPolicy.NOTHING:
await _next.Invoke(context);
break;
case IpFilterPolicy.DENY:
if (_options.Addresses.Contains(requestIpAddress))
context.Response.StatusCode = StatusCodes.Status403Forbidden;
else
await _next.Invoke(context);
break;
case IpFilterPolicy.ALLOW:
if (_options.Addresses.Contains(requestIpAddress))
await _next.Invoke(context);
else
context.Response.StatusCode = StatusCodes.Status403Forbidden;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}