如何在解析器功能级别使用GraphQL.NET实施授权? [英] How to implement authorization using GraphQL.NET at Resolver function level?

查看:160
本文介绍了如何在解析器功能级别使用GraphQL.NET实施授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何使用GraphQL.NET和ASP.NET CORE 2在解析器功能级别实现授权的示例代码和示例.

I am looking for sample code and examples regarding how to implement authorization at resolver function level using GraphQL.NET and ASP.NET CORE 2.

基本上,我试图阻止未经授权的查询的执行.

Basically I am trying to prevent the execution of query if the request is not authorized.

任何人都可以帮助我获得一些好的教程或代码示例,以作为实现的参考.

Can anyone help me to get some good tutorials or code samples as reference for the implementation.

推荐答案

对于 graphql-dotnet/authorization ,尚未发布AspNetCore的页面,请参考添加GraphQL.Server.Authorization .AspNetCore NuGet软件包#171 .

For graphql-dotnet/authorization, the page for AspNetCore has not been released, refer Add GraphQL.Server.Authorization.AspNetCore NuGet package #171.

您可以为您实现 Authorization.AspNetCore 自己使用.

You could implement Authorization.AspNetCore for your own use.

实施Authorization.AspNetCore后,您可以像这样配置Authorize:

After implement Authorization.AspNetCore, you could configure the Authorize like:

  • Startup.cs

    public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
    {
        Configuration = configuration;
        Environment = hostingEnvironment;
    }

    public IConfiguration Configuration { get; }
    public IHostingEnvironment Environment { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
        services.AddGraphQL(options =>
        {
            options.EnableMetrics = true;
            options.ExposeExceptions = Environment.IsDevelopment();

            //options.
        })
        .AddGraphQLAuthorization(options =>
        {
            options.AddPolicy("Authorized", p => p.RequireAuthenticatedUser());
            //var policy = new AuthorizationPolicyBuilder()
            //                    .
            //options.AddPolicy("Authorized", p => p.RequireClaim(ClaimTypes.Name, "Tom"));
        });
        //.AddUserContextBuilder(context => new GraphQLUserContext { User = context.User });

        services.AddSingleton<MessageSchema>();
        services.AddSingleton<MessageQuery>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseGraphQL<MessageSchema>("/graphql");
        app.UseGraphQLPlayground(new GraphQLPlaygroundOptions()
        {
            Path = "/ui/playground"
        });
        app.UseGraphiQLServer(new GraphiQLOptions
        {
            GraphiQLPath = "/ui/graphiql",
            GraphQLEndPoint = "/graphql"
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

  • 模式

  • Schema

    public class MessageQuery : ObjectGraphType<Message>
    {
        public MessageQuery()
        {
            Field(o => o.Content).Resolve(o => "This is Content").AuthorizeWith("Authorized");
            Field(o => o.SentAt);
            Field(o => o.Sub).Resolve(o => "This is Sub");
        }
    }
    

  • 有关完整的演示,请参考 GraphQLNet .

    For complete demo, refer GraphQLNet.

    这篇关于如何在解析器功能级别使用GraphQL.NET实施授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆