Comments (11)
You should not need to add InstrumentFieldsMiddleware as it is already done by UseApolloTracing.
Yes, the AddGraphQL call will register the relay types automatically, regardless of whether AddGraphTypes
is called.
from server.
Last comment: since your configuration setting is known when your application starts, this code provides a further optimization so that the InstrumentFieldsMiddleware
is not loaded in production:
services.AddGraphQL(b => {
b.AddSystemTextJson();
b.AddSchema<MySchema>();
b.AddGraphTypes();
b.AddValidationRule(NoIntrospection.Instance);
if (configuration.GetValue<bool>("GraphQL:EnableMetrics"))
{
b.UseApolloTracing();
}
b.AddAuthorization(...); // for the GraphQL.Authorization nuget package
});
This would perform most similarly to your prior code.
from server.
DefaultGraphQLExecuter and GraphQLOptions are not present with latest GraphQL.Server.All library.
IGraphQLExecuter<TSchema>
was replaced with IDocumentExecuter<TSchema>
. See the default implementation here.
However, your code can likely be replaced with a call to .UseApolloTracing
such as this snippet:
services.AddGraphQL(b => b
// other configuration stuff here
// always-on sample
.UseApolloTracing()
// sample controlled by appsettings.json
.UseApolloTracing(opts => {
var myOptions = opts.RequestedServices.GetRequiredService<IOptions<MyAppConfig>>().Value;
return myOptions.EnableApolloTracing;
})
);
In addition to a custom implementation of IDocumentLExecuter<TSchema>
, there are two other ways to implement custom code such as your prior implementation:
-
Within the
AddGraphQL
call, callConfigureExecution
. This approach can be layered, and is suggested over a custom implementation ofIDocumentExecuter<TSchema>
. See https://graphql-dotnet.github.io/docs/migrations/migration7/#4-add-code-classlanguage-textconfigureexecutioncode-builder-method-added-in-530 -
Override one or methods in the middleware (such as
ExecuteRequestAsync
) - see https://github.com/graphql-dotnet/server#graphqlhttpmiddleware . But again,ConfigureExecution
is recommended.
IOperationMessageListener
andMessageHandlingContext
are not present with latest GraphQL.Server.All library
While there is no direct replacement for the prior code, there is a new interface IWebSocketAuthenticationService
for authorization of Websocket requests. See: https://github.com/graphql-dotnet/server#authentication-for-websocket-requests for a sample code snippet.
There is also a complete sample of JWT authorization including for subscription requests:
from server.
I would like to note that .UseApolloTracing()
always installs InstrumentFieldsMiddleware
. This is because when you have a singleton schema (which is recommended), the field middleware is built with the schema when the schema is initialized, which only occurs once. The UseApolloTracing
method does not know if delegate passed to it (which executes at runtime) will be returning true
or false
so it has to assume that it may be true
. So, the field middleware is always installed.
If you have a scoped schema, there is a potential performance enhancement available -- but changing to a singleton schema would be MUCH more effective.
And if you can make the determination within your Startup.cs code, you can simply use an if
block around the call to UseApolloTracing()
as shown below to prevent the middleware from being installed:
// make determination in any way; this demonstrates using compile-time flag
#if DEBUG
var enableApolloTracing = false;
#else
var enableApolloTracing = true;
#endif
services.AddGraphQL(b => {
// other configuration stuff here
if (enableApolloTracing)
{
b.UseApolloTracing();
}
});
from server.
Hi @Shane32 ,
Thanks for your quick response and suggestions. For ApolloTracing issue, I have done the below changes based on your suggestions by using UseApolloTracing().
public static IServiceCollection AddCustomGraphQL(this IServiceCollection services,
IWebHostEnvironment hostingEnvironment, IConfiguration configuration) =>
services.AddGraphQL(
(options) =>
{
options.UseApolloTracing(x =>
{
x.EnableMetrics = configuration.GetValue<bool>("GraphQL:EnableMetrics");
if (x.EnableMetrics)
{
x.Schema.FieldMiddleware.Use(new InstrumentFieldsMiddleware());
}
x.ValidationRules = DocumentValidator.CoreRules.Concat(new[] { NoIntrospection.Instance });
return x.EnableMetrics;
})
});
I have one more question. Is there any replacement for AddRelayGraphTypes()
or it is handled as a part of AddGraphTypes()
? Please confirm.
from server.
As for NoIntrospection.Instance you probably want this instead:
.AddValidationRule(NoIntrospection.Instance)
from server.
So your AddGraphQL call might look like this:
services.AddGraphQL(b => b
.AddSystemTextJson()
.AddSchema<MySchema>()
.AddGraphTypes()
.AddValidationRule(NoIntrospection.Instance)
.UseApolloTracing(configuration.GetValue<bool>("GraphQL:EnableMetrics"))
.AddAuthorization(...) // for the GraphQL.Authorization nuget package
);
from server.
Using AddValidationRule
can be important because your code overwrites any previously added validation rules, making it necessary to run that code prior to AddAuthorization
or else the authorization rule would get dropped.
from server.
@Shane32 thanks a lot for your help.
I think I just have one last question related to below code and it is related GraphQL.Authorization library. IProvideClaimsPrincipal
interface is not available in latest GraphQL.Authorization library. Please help me on this.
public class GraphQLUserContext : IProvideClaimsPrincipal
{
/// <summary>
/// Gets the current users claims principal.
/// </summary>
public ClaimsPrincipal User { get; set; }
}
from server.
This is pulled from IResolveFieldContext.User
now, which is pulled from ExecutionOptions.User
. The server library automatically sets this value to HttpContext.User
. If you wish differently, you could do this:
services.AddGraphQL(b => b
.ConfigureExecutionOptions(options => {
options.User = /* your code here */;
})
);
Keep in mind that services, such as IHttpContextAccessor
, can be pulled from DI within that method via options.RequestServices
. The delegate can be synchronous or asynchronous. And finally, note that the transport-level authorization capabilities within the server repo will not recognize such a change; please see the readme file if you plan to use those options.
If you want to retain your existing code structure, you can either (a) implement IConfigureExecution
instead, or (b) copy in the old IProvideClaimsPrincipal
definition and write an IConfigureExecution
implementation that pulls IProvideClaimsPrincipal
from DI and applies the User
to the execution options. Let me know if you have any questions on this.
I would like to note that the authorization rule included with the server repo (AddAuthorizationRule
builder method) supports a number of new features over the GraphQL.Authorization nuget package, such as:
- Supports role-based authorization as well as policy-based authorization
- Supports 'must be authenticated' rule
- Supports 'allow anonymous' for specified fields (so that requests for only the specified field within a type are allowed when it would otherwise require authorization)
- Correctly handles following of fragments
- Faster with less memory requirements
- Better support
- Easy OOP design if you want to change how the rules/policies are checked
- But does not support authorization rules set on input object graph types
If you choose to use the new authorization rule, you may remove the GraphQL.Authorization nuget package from your project.
from server.
Sure @Shane32 , I will try out these options and get back to you if I face any issues. Thanks for all your help.
from server.
Related Issues (20)
- Using Altair UI while not connected to the internet HOT 3
- Graphql playground trying to get schema from host url instead of whole application url. HOT 2
- How to use plugins in Altair? HOT 6
- Duende Identity Server 4 / GraphQl Authorize - Always error 403 HOT 16
- Disable ReadFormOnPost by default
- Consider adding CSRF protection for GET requests
- Deprecate support of the `application/graphql+json` media type HOT 2
- Change default response content type to match current draft spec
- [Feature] Add proper support of Accept HTTP header HOT 2
- Root Query Issue HOT 4
- Return 406 on unsupported Accept header
- Come up with something for comments about Accept header
- Question: Extensibility to use other transport protocol? HOT 5
- Question about upgrading from 6xx to 7xx: VoyagerOptions HOT 4
- Subscriptions set-up netcore 6.0, GraphQL 7.1.1 HOT 6
- HttpStatus Code on GRAPHQL_VALIDATION error HOT 6
- Is there a way to change the status code of the authorization extension from 400 to 401? HOT 10
- Validation rules and Policies errors after update to v7 HOT 11
- .net core 7 AddAuthorizationRule not work HOT 29
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from server.