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

Pass attributes as metadata on binding gRPC method #484

Merged
merged 1 commit into from
Dec 14, 2021
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
1 change: 0 additions & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<Project>
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<LangVersion>7.3</LangVersion>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<VersionPrefix>4.4.0</VersionPrefix>

Expand Down
10 changes: 10 additions & 0 deletions MagicOnion.sln
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{
.github\workflows\build-release.yml = .github\workflows\build-release.yml
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{B5617CC1-55FD-4F77-BA75-9450474C6527}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AuthSample", "tests\samples\AuthSample\AuthSample.csproj", "{4D5E8486-9A0D-444A-922B-1D94FD8A820A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -159,6 +163,10 @@ Global
{E3F88CE3-F892-42AB-9D92-178BC9AD46FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E3F88CE3-F892-42AB-9D92-178BC9AD46FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E3F88CE3-F892-42AB-9D92-178BC9AD46FD}.Release|Any CPU.Build.0 = Release|Any CPU
{4D5E8486-9A0D-444A-922B-1D94FD8A820A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4D5E8486-9A0D-444A-922B-1D94FD8A820A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4D5E8486-9A0D-444A-922B-1D94FD8A820A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4D5E8486-9A0D-444A-922B-1D94FD8A820A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -186,6 +194,8 @@ Global
{34C724ED-7459-4F62-855D-90C276A6F5EA} = {1987061F-8970-4018-8D58-6932961C9EB4}
{E3F88CE3-F892-42AB-9D92-178BC9AD46FD} = {7ACC27E8-8FBE-4807-B91F-B89AF3CFF7E0}
{A8550C24-2486-49DA-8D1A-DB6BBB2E9905} = {42EBB7E4-52D7-4E57-80AD-79FDD4900E13}
{B5617CC1-55FD-4F77-BA75-9450474C6527} = {7ACC27E8-8FBE-4807-B91F-B89AF3CFF7E0}
{4D5E8486-9A0D-444A-922B-1D94FD8A820A} = {B5617CC1-55FD-4F77-BA75-9450474C6527}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D5B2E7E3-B727-40A1-BE68-7BAC9B9DE2FE}
Expand Down
1 change: 1 addition & 0 deletions src/MagicOnion.Abstractions/MagicOnion.Abstractions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>7.3</LangVersion>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\MagicOnion\opensource.snk</AssemblyOriginatorKeyFile>
<DefineConstants>NON_UNITY</DefineConstants>
Expand Down
2 changes: 1 addition & 1 deletion src/MagicOnion.Client/MagicOnion.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\MagicOnion\opensource.snk</AssemblyOriginatorKeyFile>
<LangVersion>latest</LangVersion>
<LangVersion>7.3</LangVersion>
<!--<nullable>enable</nullable>-->

<DefineConstants>TRACE;NON_UNITY</DefineConstants>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<NoWarn>1701;1702;1705;1591</NoWarn>
<DefineConstants>NON_UNITY</DefineConstants>
<LangVersion>latest</LangVersion>
<!--<nullable>enable</nullable>-->

<!-- NuGet -->
Expand Down
24 changes: 20 additions & 4 deletions src/MagicOnion.Server/Glue/MagicOnionGlueServiceBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Text;
using Grpc.AspNetCore.Server.Model;
using Grpc.Core;
using Microsoft.AspNetCore.Routing;

namespace MagicOnion.Server.Glue
{
Expand All @@ -16,24 +17,39 @@ public MagicOnionGlueServiceBinder(ServiceMethodProviderContext<TService> contex
_context = context;
}

private IList<object> GetMetadataFromHandler(Delegate handler)
{
var methodHandler = ((MethodHandler)handler.Target!);
var serviceType = methodHandler.ServiceType;

// NOTE: We need to collect Attributes for Endpoint metadata. ([Authorize], [AllowAnonymous] ...)
// https://github.com/grpc/grpc-dotnet/blob/7ef184f3c4cd62fbc3cde55e4bb3e16b58258ca1/src/Grpc.AspNetCore.Server/Model/Internal/ProviderServiceBinder.cs#L89-L98
var metadata = new List<object>();
metadata.AddRange(serviceType.GetCustomAttributes(inherit: true));
metadata.AddRange(methodHandler.MethodInfo.GetCustomAttributes(inherit: true));

metadata.Add(new HttpMethodMetadata(new[] { "POST" }, acceptCorsPreflight: true));
return metadata;
}

public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method, UnaryServerMethod<TRequest, TResponse> handler)
{
_context.AddUnaryMethod(method, Array.Empty<object>(), (_, request, context) => handler(request, context));
_context.AddUnaryMethod(method, GetMetadataFromHandler(handler), (_, request, context) => handler(request, context));
}

public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method, ClientStreamingServerMethod<TRequest, TResponse> handler)
{
_context.AddClientStreamingMethod(method, Array.Empty<object>(), (_, request, context) => handler(request, context));
_context.AddClientStreamingMethod(method, GetMetadataFromHandler(handler), (_, request, context) => handler(request, context));
}

public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method, ServerStreamingServerMethod<TRequest, TResponse> handler)
{
_context.AddServerStreamingMethod(method, Array.Empty<object>(), (_, request, stream, context) => handler(request, stream, context));
_context.AddServerStreamingMethod(method, GetMetadataFromHandler(handler), (_, request, stream, context) => handler(request, stream, context));
}

public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method, DuplexStreamingServerMethod<TRequest, TResponse> handler)
{
_context.AddDuplexStreamingMethod(method, Array.Empty<object>(), (_, request, stream, context) => handler(request, stream, context));
_context.AddDuplexStreamingMethod(method, GetMetadataFromHandler(handler), (_, request, stream, context) => handler(request, stream, context));
}
}
}
2 changes: 1 addition & 1 deletion src/MagicOnion.Server/MagicOnion.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\MagicOnion\opensource.snk</AssemblyOriginatorKeyFile>
<LangVersion>latest</LangVersion>
<nullable>enable</nullable>
<DefineConstants>TRACE;NON_UNITY</DefineConstants>
<LangVersion>default</LangVersion>

<!-- NuGet -->
<PackageId>MagicOnion.Server</PackageId>
Expand Down
3 changes: 1 addition & 2 deletions src/MagicOnion.Shared/MagicOnion.Shared.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\MagicOnion\opensource.snk</AssemblyOriginatorKeyFile>
<LangVersion>latest</LangVersion>
<!--<nullable>enable</nullable>-->
<DefineConstants>TRACE;NON_UNITY</DefineConstants>

Expand Down
3 changes: 3 additions & 0 deletions tests/MagicOnion.Server.Tests/MagicOnion.Server.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>default</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
Expand All @@ -17,6 +19,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\MagicOnion.Client\MagicOnion.Client.csproj" />
<ProjectReference Include="..\..\src\MagicOnion.Server\MagicOnion.Server.csproj" />
<ProjectReference Include="..\samples\AuthSample\AuthSample.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
73 changes: 73 additions & 0 deletions tests/MagicOnion.Server.Tests/Tests/AuthorizeServiceTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.Net.Http.Headers;
using AuthSample;
using Grpc.Core;
using Grpc.Net.Client;
using MagicOnion.Client;
using Microsoft.AspNetCore.Mvc.Testing;

namespace MagicOnion.Server.Tests.Tests
{
public class AuthorizeServiceTest : IClassFixture<WebApplicationFactory<AuthSample.Startup>>
{
private readonly WebApplicationFactory<AuthSample.Startup> _factory;

public AuthorizeServiceTest(WebApplicationFactory<AuthSample.Startup> factory)
{
_factory = factory;
}

[Fact]
public async Task Class_Authorize()
{
var httpClient = _factory.CreateDefaultClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Alice");
var client = MagicOnionClient.Create<IAuthorizeClassService>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }));
var userName = await client.GetUserNameAsync();
userName.Should().Be("Alice");
}

[Fact]
public async Task Class_Unauthorized()
{
var httpClient = _factory.CreateDefaultClient();
var client = MagicOnionClient.Create<IAuthorizeClassService>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }));
var ex = (await Assert.ThrowsAsync<RpcException>(async () => await client.GetUserNameAsync()));
ex.StatusCode.Should().Be(StatusCode.Unauthenticated);
}

[Fact]
public async Task Class_AllowAnonymous()
{
var httpClient = _factory.CreateDefaultClient();
var client = MagicOnionClient.Create<IAuthorizeClassService>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }));
(await client.AddAsync(123, 456)).Should().Be(579);
}

[Fact]
public async Task Method_Authorize()
{
var httpClient = _factory.CreateDefaultClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Alice");
var client = MagicOnionClient.Create<IAuthorizeMethodService>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }));
var userName = await client.GetUserNameAsync();
userName.Should().Be("Alice");
}

[Fact]
public async Task Method_Unauthorized()
{
var httpClient = _factory.CreateDefaultClient();
var client = MagicOnionClient.Create<IAuthorizeMethodService>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }));
var ex = (await Assert.ThrowsAsync<RpcException>(async () => await client.GetUserNameAsync()));
ex.StatusCode.Should().Be(StatusCode.Unauthenticated);
}

[Fact]
public async Task Method_AllowAnonymous()
{
var httpClient = _factory.CreateDefaultClient();
var client = MagicOnionClient.Create<IAuthorizeMethodService>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }));
(await client.AddAsync(123, 456)).Should().Be(579);
}
}
}
47 changes: 47 additions & 0 deletions tests/MagicOnion.Server.Tests/Tests/AuthorizeStreamingHubTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using AuthSample;
using Grpc.Core;
using Grpc.Net.Client;
using MagicOnion.Client;
using Microsoft.AspNetCore.Mvc.Testing;

namespace MagicOnion.Server.Tests.Tests
{
public class AuthorizeStreamingHubTest : IClassFixture<WebApplicationFactory<AuthSample.Startup>>, IAuthorizeHubReceiver
{
private readonly WebApplicationFactory<AuthSample.Startup> _factory;

public AuthorizeStreamingHubTest(WebApplicationFactory<AuthSample.Startup> factory)
{
_factory = factory;
}

[Fact]
public async Task Authorize_Connect()
{
var httpClient = _factory.CreateDefaultClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Alice");
var client = await StreamingHubClient.ConnectAsync<IAuthorizeHub, IAuthorizeHubReceiver>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }), this);
var userName = await client.GetUserNameAsync();
userName.Should().Be("Alice");
}

[Fact]
public async Task Unauthenticated_Connect()
{
var httpClient = _factory.CreateDefaultClient();

var ex = await Assert.ThrowsAsync<RpcException>(async () =>
{
var client = await StreamingHubClient.ConnectAsync<IAuthorizeHub, IAuthorizeHubReceiver>(GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions() { HttpClient = httpClient }), this);
});

ex.StatusCode.Should().Be(StatusCode.Unauthenticated);
}
}
}
2 changes: 2 additions & 0 deletions tests/MagicOnion.Server.Tests/_GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
global using FluentAssertions;
global using Xunit;
13 changes: 13 additions & 0 deletions tests/samples/AuthSample/AuthSample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\MagicOnion.Server\MagicOnion.Server.csproj" />
</ItemGroup>

</Project>
26 changes: 26 additions & 0 deletions tests/samples/AuthSample/FakeAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Security.Claims;
using System.Security.Principal;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;

namespace AuthSample;

public class FakeAuthenticationHandler : AuthenticationHandler<FakeAuthenticationHandlerOptions>
{
public FakeAuthenticationHandler(IOptionsMonitor<FakeAuthenticationHandlerOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (Context.Request.Headers.TryGetValue("Authorization", out var value) && value == "Bearer Alice")
{
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new GenericIdentity("Alice")), "Fake")));
}

return Task.FromResult(AuthenticateResult.Fail("Unauthorized"));
}
}

public class FakeAuthenticationHandlerOptions : AuthenticationSchemeOptions { }
51 changes: 51 additions & 0 deletions tests/samples/AuthSample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.Encodings.Web;

namespace AuthSample;

public class Program
{
public static void Main(string[] args) => CreateWebHostBuilder(args).Build().Run();

// Do not change. This is the pattern our test infrastructure uses to initialize a IWebHostBuilder from
// a users app.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.AddDebug();
})
.UseKestrel()
.UseIISIntegration();
}


public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddMagicOnion(new [] { typeof(Startup).Assembly });

services.AddAuthentication("Fake")
.AddScheme<FakeAuthenticationHandlerOptions, FakeAuthenticationHandler>("Fake", options => { });

services.AddAuthorization();
}

public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapMagicOnionService();
});
}
}
Loading