51 lines
1.7 KiB
C#
51 lines
1.7 KiB
C#
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
namespace AMWD.Common.AspNetCore.Security.PathProtection
|
|
{
|
|
/// <summary>
|
|
/// Implements a check to provide protected paths.
|
|
/// </summary>
|
|
public class ProtectedPathMiddleware
|
|
{
|
|
private readonly RequestDelegate next;
|
|
private readonly PathString path;
|
|
private readonly string policyName;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="ProtectedPathExtensions"/> class.
|
|
/// </summary>
|
|
/// <param name="next">The following delegate in the process chain.</param>
|
|
/// <param name="options">The options to configure the middleware.</param>
|
|
public ProtectedPathMiddleware(RequestDelegate next, ProtectedPathOptions options)
|
|
{
|
|
this.next = next;
|
|
path = options.Path;
|
|
policyName = options.PolicyName;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The delegate invokation.
|
|
/// Performs the protection check.
|
|
/// </summary>
|
|
/// <param name="httpContext">The corresponding HTTP context.</param>
|
|
/// <param name="authorizationService">The <see cref="IAuthorizationService"/>.</param>
|
|
/// <returns>An awaitable task.</returns>
|
|
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);
|
|
}
|
|
}
|
|
}
|