2023-03-03 21:47:23 +00:00
|
|
|
using Elsa.Http.Contracts;
|
2022-05-26 10:47:31 +00:00
|
|
|
using Elsa.Http.Models;
|
2023-05-01 10:06:51 +00:00
|
|
|
using JetBrains.Annotations;
|
2022-03-09 23:19:00 +00:00
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
|
|
2022-11-19 21:30:43 +00:00
|
|
|
namespace Elsa.Http.Handlers;
|
|
|
|
|
|
2023-05-01 10:06:51 +00:00
|
|
|
/// <summary>
|
|
|
|
|
/// An <see cref="IHttpEndpointAuthorizationHandler"/> that uses the <see cref="IAuthorizationService"/> to authorize an inbound HTTP request.
|
|
|
|
|
/// </summary>
|
|
|
|
|
[PublicAPI]
|
2022-11-19 21:30:43 +00:00
|
|
|
public class AuthenticationBasedHttpEndpointAuthorizationHandler : IHttpEndpointAuthorizationHandler
|
2022-03-09 23:19:00 +00:00
|
|
|
{
|
2022-11-19 21:30:43 +00:00
|
|
|
private readonly IAuthorizationService _authorizationService;
|
2023-05-01 10:06:51 +00:00
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Initializes a new instance of the <see cref="AuthenticationBasedHttpEndpointAuthorizationHandler"/> class.
|
|
|
|
|
/// </summary>
|
2022-11-19 21:30:43 +00:00
|
|
|
public AuthenticationBasedHttpEndpointAuthorizationHandler(IAuthorizationService authorizationService) => _authorizationService = authorizationService;
|
2022-03-09 23:19:00 +00:00
|
|
|
|
2023-05-01 10:06:51 +00:00
|
|
|
/// <inheritdoc />
|
2022-11-19 21:30:43 +00:00
|
|
|
public async ValueTask<bool> AuthorizeAsync(AuthorizeHttpEndpointContext context)
|
|
|
|
|
{
|
|
|
|
|
var httpContext = context.HttpContext;
|
|
|
|
|
var user = httpContext.User;
|
|
|
|
|
var identity = user.Identity;
|
2022-03-09 23:19:00 +00:00
|
|
|
|
2022-11-19 21:30:43 +00:00
|
|
|
if (identity == null)
|
|
|
|
|
return false;
|
2023-03-08 08:49:43 +00:00
|
|
|
|
2022-11-19 21:30:43 +00:00
|
|
|
if (identity.IsAuthenticated == false)
|
|
|
|
|
return false;
|
2022-03-09 23:19:00 +00:00
|
|
|
|
2023-03-08 08:49:43 +00:00
|
|
|
if (string.IsNullOrWhiteSpace(context.Policy))
|
2022-11-19 21:30:43 +00:00
|
|
|
return identity.IsAuthenticated;
|
2022-03-09 23:19:00 +00:00
|
|
|
|
2023-03-08 08:49:43 +00:00
|
|
|
var authorizationResult = await _authorizationService.AuthorizeAsync(user,
|
|
|
|
|
new { workflowInstanceId = context.WorkflowInstanceId }, context.Policy!);
|
|
|
|
|
|
2022-11-19 21:30:43 +00:00
|
|
|
return authorizationResult.Succeeded;
|
2022-03-09 23:19:00 +00:00
|
|
|
}
|
|
|
|
|
}
|