Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perform policy based authorization on transport http controller #31

Merged
merged 3 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion Transport/Stateflows.Transport.Http/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Stateflows.Common.Interfaces;
using Stateflows.Common.Extensions;
using Stateflows.Common.Transport.Classes;
using Microsoft.AspNetCore.Authorization;

namespace Stateflows.Transport.Http
{
Expand All @@ -28,11 +29,14 @@ public static IEndpointRouteBuilder MapStateflowsHttpTransport(this IEndpointRou
INotificationsHub hub
) =>
{

var responseTime = DateTime.Now;
using var reader = new StreamReader(context.Request.Body);
var body = await reader.ReadToEndAsync();
var input = StateflowsJsonConverter.DeserializeObject<StateflowsRequest>(body);

//temporary authorization solution
if (!AuthorizeUser(context, input.Event))
return Results.Unauthorized();
var behaviorId = new BehaviorId(input.BehaviorId.Type, input.BehaviorId.Name, input.BehaviorId.Instance);
if (locator.TryLocateBehavior(behaviorId, out var behavior))
{
Expand Down Expand Up @@ -77,5 +81,25 @@ INotificationsHub hub

return builder;
}

private static bool AuthorizeUser(HttpContext context, Event stateflowsEvent)
{
AuthorizeAttribute? authAttribute = (AuthorizeAttribute?)Attribute.GetCustomAttribute(stateflowsEvent.GetType(),
typeof(AuthorizeAttribute));
if (authAttribute != null)
{
var policy = authAttribute.Policy;
var user = context.User;
if (policy == null && user != null && user.Identity!.IsAuthenticated)
return true;
if (user != null && user.Claims.Any(c => c.Value.Equals(policy)))
{
return true;
}
return false;
}
return true;

}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
Expand Down Expand Up @@ -37,6 +37,10 @@
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="8.0.10" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Core\Stateflows.Transport.Common\Stateflows.Common.Transport.csproj" />
<ProjectReference Include="..\..\Core\Stateflows\Stateflows.csproj" />
Expand Down
Loading