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

Add authentication [WIP] #42

Merged
merged 9 commits into from
Mar 6, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
68 changes: 35 additions & 33 deletions src/GraphiQl/GraphiQlExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,80 +3,82 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;

namespace GraphiQl
{
public static class GraphiQlExtensions
{
private const string DefaultPath = "/graphql";
private const string DefaultGraphQlPath = "/graphql";

public static IServiceCollection AddGraphiQl(this IServiceCollection services)
=> services.AddGraphiQl(null);

public static IServiceCollection AddGraphiQl(this IServiceCollection services, Action<GraphiQlOptions> configure)
{
if (configure != null)
{
services.Configure(configure);
}

services.TryAdd(ServiceDescriptor.Transient<IConfigureOptions<GraphiQlOptions>, GraphiQlOptionsSetup>());

return services;
}

public static IApplicationBuilder UseGraphiQl(this IApplicationBuilder app)
=> UseGraphiQl(app, DefaultPath);
=> app.UseGraphiQl(DefaultGraphQlPath);

public static IApplicationBuilder UseGraphiQl(this IApplicationBuilder app, string path)
=> UseGraphiQl(app, path, null);
=> app.UseGraphiQl(path, null);

/// <param name="app"></param>
/// <param name="path"></param>
/// <param name="apiPath">In some scenarios it makes sense to specify the API path and file server path independently
/// Examples: hosting in IIS in a virtual application (myapp.com/1.0/...) or hosting API and documentation separately</param>
public static IApplicationBuilder UseGraphiQl(this IApplicationBuilder app, string path, string apiPath)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException(nameof(path));
var options = app.ApplicationServices.GetService<IOptions<GraphiQlOptions>>().Value;

if (path.EndsWith("/"))
if (options.GraphiQlPath != null && options.GraphiQlPath.EndsWith("/"))
{
throw new ArgumentException("GraphiQL path must not end in a slash", nameof(path));
}

var filePath = $"{path}/graphql-path.js";
var uri = !string.IsNullOrWhiteSpace(apiPath) ? apiPath : path;
app.Map(filePath, x => WritePathJavaScript(x, uri));
var filePath = $"{options.GraphiQlPath}/graphql-path.js";
var graphQlPath = !string.IsNullOrWhiteSpace(options.GraphQlApiPath) ? options.GraphQlApiPath : DefaultGraphQlPath;
app.Map(filePath, x => WritePathJavaScript(x, graphQlPath));

return UseGraphiQlImp(app, x => x.SetPath(path));
return UseGraphiQlImp(app, options);
}

private static IApplicationBuilder UseGraphiQlImp(this IApplicationBuilder app, Action<GraphiQlConfig> setConfig)
private static IApplicationBuilder UseGraphiQlImp(this IApplicationBuilder app, GraphiQlOptions options)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (setConfig == null)
throw new ArgumentNullException(nameof(setConfig));

var config = new GraphiQlConfig();
setConfig(config);

var fileServerOptions = new FileServerOptions
{
RequestPath = config.Path,
FileProvider = BuildFileProvider(),
RequestPath = options.GraphiQlPath,
FileProvider = new EmbeddedFileProvider(typeof(GraphiQlExtensions).GetTypeInfo().Assembly, "GraphiQl.assets"),
EnableDefaultFiles = true,
StaticFileOptions = {ContentTypeProvider = new FileExtensionContentTypeProvider()}
};

app.UseMiddleware<GraphiQlMiddleware>();
app.UseFileServer(fileServerOptions);

return app;
}

private static IFileProvider BuildFileProvider()
{
var assembly = typeof(GraphiQlExtensions).GetTypeInfo().Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(assembly, "GraphiQl.assets");

var fileProvider = new CompositeFileProvider(
embeddedFileProvider
);

return fileProvider;
}

private static void WritePathJavaScript(IApplicationBuilder app, string path)
{
private static void WritePathJavaScript(IApplicationBuilder app, string path) =>
app.Run(h =>
{
h.Response.ContentType = "application/javascript";
return h.Response.WriteAsync($"var graphqlPath='{path}';");
});
}
}
}
31 changes: 31 additions & 0 deletions src/GraphiQl/GraphiQlMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace GraphiQl
{
public class GraphiQlMiddleware
{
private readonly RequestDelegate _next;
private readonly GraphiQlOptions _options;

public GraphiQlMiddleware(RequestDelegate next, IOptions<GraphiQlOptions> options)
{
_next = next;
_options = options.Value;
}

public async Task Invoke(HttpContext context)
{
if (context.Request.Path.Equals(_options.GraphiQlPath, StringComparison.OrdinalIgnoreCase)
&& _options.IsAuthenticated != null
&& !await _options.IsAuthenticated.Invoke(context))
{
return;
}

await _next(context);
}
}
}
42 changes: 42 additions & 0 deletions src/GraphiQl/GraphiQlOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace GraphiQl
{
public class GraphiQlOptions
{
public string GraphiQlPath { get; set; }

public string GraphQlApiPath { get; set; }

public Func<HttpContext, Task<bool>> IsAuthenticated { get; set; }

public GraphiQlOptions()
{
GraphiQlPath = "/graphql";
GraphQlApiPath = "/graphql";
}
}

public class GraphiQlOptionsSetup : IConfigureOptions<GraphiQlOptions>
{
public void Configure(GraphiQlOptions options)
{
if (options.GraphiQlPath == null)
{
options.GraphiQlPath = "/graphql";
}
else
{
var x = options.GraphiQlPath;
}

if (options.GraphQlApiPath == null)
{
options.GraphQlApiPath = "/graphql";
}
}
}
}
3 changes: 0 additions & 3 deletions tests/GraphiQl.Demo/GraphiQl.Demo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="GraphQL" Version="2.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
Expand Down
12 changes: 2 additions & 10 deletions tests/GraphiQl.Demo/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand All @@ -22,6 +21,7 @@ public Startup(IConfiguration configuration)
public void ConfigureServices(IServiceCollection services)
{
services
.AddGraphiQl()
.AddMvc()
.AddNewtonsoftJson(
options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
Expand All @@ -30,15 +30,7 @@ public void ConfigureServices(IServiceCollection services)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{

/*
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
*/

app.UseGraphiQl(GraphQlPath);
app.UseGraphiQl();
app.UseRouting().UseEndpoints(
routing => routing.MapControllers()
);
Expand Down
68 changes: 68 additions & 0 deletions tests/GraphiQl.Tests/AuthenticationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System.Threading;
using System.Threading.Tasks;
using GraphiQl.Demo;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;

namespace GraphiQl.Tests
{
public class AuthenticationTests : BaseTest, IAsyncLifetime
{
private readonly IWebHost _host;

public AuthenticationTests()
{
_host = WebHost.CreateDefaultBuilder()
.ConfigureServices(x => { x.AddTransient<IConfigureOptions<GraphiQlOptions>,GraphiQlTestOptionsSetup>(); })
.UseStartup<Startup>()
.UseKestrel()
.UseUrls("http://*:5001")
.Build();
}

[Fact]
public void RequiresAuthentication()
{
// Arrange + Act
var result = string.Empty;
RunTest( async driver =>
{
Driver.Navigate().GoToUrl("http://localhost:5001/graphql");
Thread.Sleep(2000);
result = Driver.PageSource;
});

// Assert
result.ShouldContain("This page requires authentication");
}

public async Task InitializeAsync()
=> await _host.StartAsync().ConfigureAwait(false);

public Task DisposeAsync()
{
_host.Dispose();
return Task.CompletedTask;
}

internal class GraphiQlTestOptionsSetup : IConfigureOptions<GraphiQlOptions>
{
public void Configure(GraphiQlOptions options)
{
options.IsAuthenticated = context =>
{
context.Response.Clear();
context.Response.StatusCode = 400;
context.Response.WriteAsync("This page requires authentication");

return Task.FromResult(false);
};
}
}
}
}
17 changes: 10 additions & 7 deletions tests/GraphiQl.Tests/BaseTest.cs
Original file line number Diff line number Diff line change
@@ -1,35 +1,38 @@
using System;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace GraphiQl.Tests
{
public abstract class BaseTest
{
protected ChromeDriver Driver { get; }
protected bool RunHeadless { get; set; } = true;

protected BaseTest(bool runHeadless)
protected BaseTest()
{
var options = new ChromeOptions();
/*
options.AddArgument("--remote-debugging-port=9222");
*/
options.AddArgument("--disable-dev-shm-usage");
options.AddArgument("--no-sandbox");

if (runHeadless)
if (RunHeadless)
options.AddArgument("--headless");

Driver = new ChromeDriver(options);
}

protected async Task RunTest(Func<ChromeDriver, Task> execute)
protected void RunTest(Action<IWebDriver> execute)
{
try
{
await execute(Driver);
execute(Driver);
}
catch (Exception)
catch (Exception ex)
{
throw;
throw ex;
}
finally
{
Expand Down
10 changes: 5 additions & 5 deletions tests/GraphiQl.Tests/GraphQlTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;
using System.Text.Json;
using System.Threading.Tasks;
using System.Threading;
using GraphiQl.Tests.Fixtures;
using Shouldly;
using Xunit;
Expand All @@ -11,13 +11,13 @@ public class GraphQlTests : BaseTest, IClassFixture<HostFixture>
{
private readonly HostFixture _fixture;

public GraphQlTests(HostFixture fixture) : base(runHeadless: true)
public GraphQlTests(HostFixture fixture)
{
_fixture = fixture;
}

[Fact]
public async Task CanQueryGraphQl()
public void CanQueryGraphQl()
{
// TODO: Use PageModel

Expand All @@ -26,13 +26,13 @@ public async Task CanQueryGraphQl()
var query = @"{hero{id,name}}";

// Act
await RunTest(async driver =>
RunTest( driver =>
{
Driver.Navigate().GoToUrl(_fixture.GraphiQlUri + Uri.EscapeDataString(query));
var button = Driver.FindElementByClassName("execute-button");
button?.Click();

await Task.Delay(2000);
Thread.Sleep(2000);

// UGH!
result = Driver
Expand Down
Loading