-
-
Notifications
You must be signed in to change notification settings - Fork 38
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
Using dependency injection in AuthorizationRequirement #54
Comments
I ended adding to my Then, when implementing my HttpContext httpContext = ((GraphQLUserContext)context.UserContext).HttpContext;
var myService = (IMyService)httpContext.RequestServices.GetService(typeof(IMyService)); Is there a better way of doing so? |
Here's an alternative way to do it: public class MyReq : IAuthorizationRequirement
{
private readonly IHttpContextAccessor accessor;
public MyReq(IHttpContextAccessor accessor)
{
this.accessor = accessor;
}
public Task Authorize(AuthorizationContext context)
{
return Task.CompletedTask;
}
}
public static class GraphQLAuthExtensions
{
public static void AddGraphQLAuth(this IServiceCollection services, Action<AuthorizationSettings, IServiceProvider> configure)
{
services.AddHttpContextAccessor();
services.AddTransient<IAuthorizationEvaluator, AuthorizationEvaluator>();
services.AddTransient<IValidationRule, AuthorizationValidationRule>();
services.AddTransient<MyReq>();
services.TryAddTransient(s =>
{
var authSettings = new AuthorizationSettings();
configure(authSettings, s);
return authSettings;
});
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddGraphQLAuth((_, s) =>
{
_.AddPolicy("SomePolicy", p => p.AddRequirement(s.GetService<MyReq>()));
});
} |
Instead of services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); you can use special method services.AddHttpContextAccessor(); from Microsoft.AspNetCore.Http what does exacly the same thing. |
I updated |
Enabling scope validation on DI-container may help to find such problems. |
Thanks! I'll do it this way |
this is incredibly helpful @joacoleza , do you have an example of how you added the service you want injected to the httpcontext and how you retrieve it out of the httpcontext? i am getting some type errors |
for example in my AddGraphQLAuth i have
and in my requirement i attempt to access it by |
I no longer have access to the code where this was implemented. Sorry I couldn’t be more help. |
Hi, as I need one registered service to evaluate the authorization, is there a way to use Dependency Injection when implementing
IAuthorizationRequirement
?I want to achieve something similar to handlers in in ASP.NET Core.
Thanks!
The text was updated successfully, but these errors were encountered: