Skip to content
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
14 changes: 13 additions & 1 deletion GraphQL.Server.sln
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Transports.Subscriptions.Ab
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ui.Voyager", "src\Ui.Voyager\Ui.Voyager.csproj", "{B2C278E4-6A1A-4F83-AE53-C9469B4056EE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core", "src\Core\Core.csproj", "{4872A0F3-FA1B-410B-834C-8A5653621E56}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core", "src\Core\Core.csproj", "{4872A0F3-FA1B-410B-834C-8A5653621E56}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authorization.AspNetCore", "src\Authorization.AspNetCore\Authorization.AspNetCore.csproj", "{7A71AF0D-FE5F-4607-A6F6-960FD98CF840}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authorization.AspNetCore.Tests", "tests\Authorization.AspNetCore.Tests\Authorization.AspNetCore.Tests.csproj", "{741DEEE6-FD0B-4F99-8A6F-43584B3E8D5F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -89,6 +93,14 @@ Global
{4872A0F3-FA1B-410B-834C-8A5653621E56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4872A0F3-FA1B-410B-834C-8A5653621E56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4872A0F3-FA1B-410B-834C-8A5653621E56}.Release|Any CPU.Build.0 = Release|Any CPU
{7A71AF0D-FE5F-4607-A6F6-960FD98CF840}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7A71AF0D-FE5F-4607-A6F6-960FD98CF840}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7A71AF0D-FE5F-4607-A6F6-960FD98CF840}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7A71AF0D-FE5F-4607-A6F6-960FD98CF840}.Release|Any CPU.Build.0 = Release|Any CPU
{741DEEE6-FD0B-4F99-8A6F-43584B3E8D5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{741DEEE6-FD0B-4F99-8A6F-43584B3E8D5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{741DEEE6-FD0B-4F99-8A6F-43584B3E8D5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{741DEEE6-FD0B-4F99-8A6F-43584B3E8D5F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
28 changes: 28 additions & 0 deletions src/Authorization.AspNetCore/Authorization.AspNetCore.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup Label="Build">
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<AssemblyName>GraphQL.Server.Authorization.AspNetCore</AssemblyName>
<RootNamespace>GraphQL.Server.Authorization.AspNetCore</RootNamespace>
<Product>graphql-dotnet server</Product>
<Company>graphql-dotnet</Company>
<Authors>Pekka Heikura</Authors>
<Description>HTTP authorization middleware for graphql</Description>
<PackageProjectUrl>https://github.com/graphql-dotnet/server</PackageProjectUrl>
<RepositoryUrl>https://github.com/graphql-dotnet/server</RepositoryUrl>
<RepositoryType>Git</RepositoryType>
<PackageTags>GraphQL authentication authorization middleware</PackageTags>
<Copyright>Pekka Heikura</Copyright>
</PropertyGroup>

<ItemGroup Label="Package References">
<PackageReference Include="GraphQL" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.0.0" />
</ItemGroup>

<ItemGroup Label="Project References">
<ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions src/Authorization.AspNetCore/AuthorizationMetadataExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Collections.Generic;
using GraphQL.Builders;
using GraphQL.Types;

namespace GraphQL.Server.Authorization.AspNetCore
{
public static class AuthorizationMetadataExtensions
{
public const string PolicyKey = "Authorization__Policies";

public static bool RequiresAuthorization(this IProvideMetadata type)
{
var policies = GetPolicies(type);
return policies != null && policies.Count > 0;
}

public static void AuthorizeWith(this IProvideMetadata type, string policy)
{
var list = GetPolicies(type) ?? new List<string>();
list.Fill(policy);
type.Metadata[PolicyKey] = list;
}

public static FieldBuilder<TSourceType, TReturnType> AuthorizeWith<TSourceType, TReturnType>(
this FieldBuilder<TSourceType, TReturnType> builder, string policy)
{
builder.FieldType.AuthorizeWith(policy);
return builder;
}

public static List<string> GetPolicies(this IProvideMetadata type) =>
type.GetMetadata<List<string>>(PolicyKey, null);
}
}
173 changes: 173 additions & 0 deletions src/Authorization.AspNetCore/AuthorizationValidationRule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GraphQL.Language.AST;
using GraphQL.Types;
using GraphQL.Validation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Http;

namespace GraphQL.Server.Authorization.AspNetCore
{
public class AuthorizationValidationRule : IValidationRule
{
private readonly IAuthorizationService _authorizationService;
private readonly IHttpContextAccessor _httpContextAccessor;

public AuthorizationValidationRule(
IAuthorizationService authorizationService,
IHttpContextAccessor httpContextAccessor)
{
_authorizationService = authorizationService;
_httpContextAccessor = httpContextAccessor;
}

public INodeVisitor Validate(ValidationContext context)
{
return new EnterLeaveListener(_ =>
{
var operationType = OperationType.Query;

// this could leak info about hidden fields or types in error messages
// it would be better to implement a filter on the Schema so it
// acts as if they just don't exist vs. an auth denied error
// - filtering the Schema is not currently supported

_.Match<Operation>(astType =>
{
operationType = astType.OperationType;

var type = context.TypeInfo.GetLastType();
AuthorizeAsync(astType, type, context, operationType).GetAwaiter().GetResult();
});

_.Match<ObjectField>(objectFieldAst =>
{
var argumentType = context.TypeInfo.GetArgument().ResolvedType.GetNamedType() as IComplexGraphType;
if (argumentType == null)
{
return;
}

var fieldType = argumentType.GetField(objectFieldAst.Name);
AuthorizeAsync(objectFieldAst, fieldType, context, operationType).GetAwaiter().GetResult();
});

_.Match<Field>(fieldAst =>
{
var fieldDef = context.TypeInfo.GetFieldDef();
if (fieldDef == null)
{
return;
}

// check target field
AuthorizeAsync(fieldAst, fieldDef, context, operationType).GetAwaiter().GetResult();
// check returned graph type
AuthorizeAsync(fieldAst, fieldDef.ResolvedType, context, operationType).GetAwaiter().GetResult();
});
});
}

private async Task AuthorizeAsync(
INode node,
IProvideMetadata type,
ValidationContext context,
OperationType operationType)
{
if (type == null || !type.RequiresAuthorization())
{
return;
}

var policyNames = type.GetPolicies();
if (policyNames.Count == 0)
{
return;
}

var tasks = new List<Task<AuthorizationResult>>(policyNames.Count);
foreach (var policyName in policyNames)
{
var task = _authorizationService.AuthorizeAsync(this._httpContextAccessor.HttpContext.User, policyName);
tasks.Add(task);
}
await Task.WhenAll(tasks);

foreach (var task in tasks)
{
var result = task.Result;
if (!result.Succeeded)
{
var stringBuilder = new StringBuilder("You are not authorized to run this ");
stringBuilder.Append(operationType.ToString().ToLower());
stringBuilder.AppendLine(".");

foreach (var failure in result.Failure.FailedRequirements)
{
AppendFailureLine(stringBuilder, failure);
}

context.ReportError(
new ValidationError(context.OriginalQuery, "authorization", stringBuilder.ToString(), node));
}
}
}

private static void AppendFailureLine(
StringBuilder stringBuilder,
IAuthorizationRequirement authorizationRequirement)
{
switch (authorizationRequirement)
{
case ClaimsAuthorizationRequirement claimsAuthorizationRequirement:
stringBuilder.Append("Required claim '");
stringBuilder.Append(claimsAuthorizationRequirement.ClaimType);
if (claimsAuthorizationRequirement.AllowedValues == null || !claimsAuthorizationRequirement.AllowedValues.Any())
{
stringBuilder.AppendLine("' is not present.");
}
else
{
stringBuilder.Append("' with any value of '");
stringBuilder.Append(string.Join(", ", claimsAuthorizationRequirement.AllowedValues));
stringBuilder.AppendLine("' is not present.");
}
break;
case DenyAnonymousAuthorizationRequirement denyAnonymousAuthorizationRequirement:
stringBuilder.AppendLine("The current user must be authenticated.");
break;
case NameAuthorizationRequirement nameAuthorizationRequirement:
stringBuilder.Append("The current user name must match the name '");
stringBuilder.Append(nameAuthorizationRequirement.RequiredName);
stringBuilder.AppendLine("'.");
break;
case OperationAuthorizationRequirement operationAuthorizationRequirement:
stringBuilder.Append("Required operation '");
stringBuilder.Append(operationAuthorizationRequirement.Name);
stringBuilder.AppendLine("' was not present.");
break;
case RolesAuthorizationRequirement rolesAuthorizationRequirement:
if (rolesAuthorizationRequirement.AllowedRoles == null || !rolesAuthorizationRequirement.AllowedRoles.Any())
{
// This should never happen.
stringBuilder.AppendLine("Required roles are not present.");
}
else
{
stringBuilder.Append("Required roles '");
stringBuilder.Append(string.Join(", ", rolesAuthorizationRequirement.AllowedRoles));
stringBuilder.AppendLine("' are not present.");
}
break;
default:
stringBuilder.Append("Requirement '");
stringBuilder.Append(authorizationRequirement.GetType().Name);
stringBuilder.AppendLine("' was not satisfied.");
break;
}
}
}
}
19 changes: 19 additions & 0 deletions src/Authorization.AspNetCore/GraphQLAuthorizeAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using GraphQL.Utilities;

namespace GraphQL.Server.Authorization.AspNetCore
{
public class GraphQLAuthorizeAttribute : GraphQLAttribute
{
public string Policy { get; set; }

public override void Modify(TypeConfig type)
{
type.AuthorizeWith(Policy);
}

public override void Modify(FieldConfig field)
{
field.AuthorizeWith(Policy);
}
}
}
44 changes: 44 additions & 0 deletions src/Authorization.AspNetCore/GraphQlBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using GraphQL.Server.Authorization.AspNetCore;
using GraphQL.Validation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace GraphQL.Server
{
public static class GraphQLBuilderExtensions
{
/// <summary>
/// Adds the GraphQL authorization.
/// </summary>
/// <param name="builder">The GraphQL builder.</param>
/// <returns></returns>
public static IGraphQLBuilder AddGraphQLAuthorization(this IGraphQLBuilder builder)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder
.Services
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add this line in these methods to make sure IHttpContextAccessor is registered. It is not by default.

builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

.AddTransient<IValidationRule, AuthorizationValidationRule>()
.AddAuthorization();
return builder;
}

/// <summary>
/// Adds the GraphQL authorization.
/// </summary>
/// <param name="builder">The GraphQL builder.</param>
/// <param name="options">An action delegate to configure the provided <see cref="AuthorizationOptions"/>.</param>
/// <returns>The GraphQL builder.</returns>
public static IGraphQLBuilder AddGraphQLAuthorization(this IGraphQLBuilder builder, Action<AuthorizationOptions> options)
{
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder
.Services
.AddTransient<IValidationRule, AuthorizationValidationRule>()
.AddAuthorization(options);
return builder;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup Label="Build">
<TargetFrameworks>netcoreapp2.0</TargetFrameworks>
<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup Label="Package References">
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
<PackageReference Include="Moq" Version="4.9.0" />
<PackageReference Include="Shouldly" Version="3.0.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>

<ItemGroup Label="Project References">
<ProjectReference Include="..\..\src\Authorization.AspNetCore\Authorization.AspNetCore.csproj" />
</ItemGroup>

<PropertyGroup>
<AssemblyName>GraphQL.Server.Authorization.AspNetCore.Tests</AssemblyName>
</PropertyGroup>

<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>

</Project>
Loading