Using ASP.NET Core controllers, you can add e.g. the attribute [Authorize] to methods or whole classes to prevent unauthorized access.
The following example extends this functionality by allowing access if the client user resides in the local network.
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 |
namespace myns.Helpers { public class AuthorizeOrInternalAttribute : TypeFilterAttribute { /// <summary> /// If set, user is able to access the controller method if logged in or requests from LAN /// </summary> public AuthorizeOrInternalAttribute() : base(typeof(AuthorizeOrInternalFilter)) { } } public class AuthorizeOrInternalFilter : IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { var internalIps = new[] { "::1", "127.0.0.1", "192.168." }; var remoteIp = context.HttpContext.Connection.RemoteIpAddress.ToString(); var isLAN = internalIps.Any(iI => remoteIp.StartsWith(iI)); if (!isLAN) if (context.HttpContext.User == null) context.Result = new ForbidResult(); } } } |
1 2 3 4 5 6 |
[HttpGet("[action]")] [AuthorizeOrInternal] public User Details() { return this.GetAnyDetails(); } |
Comments