This entry has been published on 2019-12-09 and may be out of date.
Last Updated on 2019-12-09.
[:en]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.
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(); } } }
[HttpGet("[action]")] [AuthorizeOrInternal] public User Details() { return this.GetAnyDetails(); }
Reference[:]