using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace AMWD.Common.AspNetCore.Security.PathProtection { /// /// Implements a check to provide protected paths. /// public class ProtectedPathMiddleware { private readonly RequestDelegate _next; private readonly PathString _path; private readonly string _policyName; /// /// Initializes a new instance of the class. /// /// The following delegate in the process chain. /// The options to configure the middleware. public ProtectedPathMiddleware(RequestDelegate next, ProtectedPathOptions options) { _next = next; _path = options.Path; _policyName = options.PolicyName; } /// /// The delegate invokation. /// Performs the protection check. /// /// The corresponding HTTP context. /// The . /// An awaitable task. public async Task InvokeAsync(HttpContext httpContext, IAuthorizationService authorizationService) { if (httpContext.Request.Path.StartsWithSegments(_path)) { var result = await authorizationService.AuthorizeAsync(httpContext.User, null, _policyName).ConfigureAwait(false); if (!result.Succeeded) { await httpContext.ChallengeAsync().ConfigureAwait(false); return; } } await _next.Invoke(httpContext).ConfigureAwait(false); } } }