-
Notifications
You must be signed in to change notification settings - Fork 165
Add GraphQL.Server.Authorization.AspNetCore NuGet package #171
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f4e58ab
Add GraphQL.Server.Authorization.AspNetCore NuGet package
RehanSaeed 4dd18ad
Rename file for consistency.
RehanSaeed 3233cbb
Reference ASP.NET Core 2.0
RehanSaeed 075fc5b
Default metadata to null instead of creating new lists.
RehanSaeed 3f943f1
Use IHttpContextAccessor instead of IProvideClaimsPrincipal
RehanSaeed b54c55d
TryAdd IHttpContextAccessor
RehanSaeed File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
src/Authorization.AspNetCore/Authorization.AspNetCore.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
34
src/Authorization.AspNetCore/AuthorizationMetadataExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
173
src/Authorization.AspNetCore/AuthorizationValidationRule.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| .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; | ||
| } | ||
| } | ||
| } | ||
31 changes: 31 additions & 0 deletions
31
tests/Authorization.AspNetCore.Tests/Authorization.AspNetCore.Tests.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
IHttpContextAccessoris registered. It is not by default.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.