首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在解析器函数级别使用GraphQL.NET实现授权?

如何在解析器函数级别使用GraphQL.NET实现授权?
EN

Stack Overflow用户
提问于 2018-11-29 19:02:12
回答 2查看 8.1K关注 0票数 7

我正在寻找有关如何使用GraphQL.NET和ASP.NET Core2在解析器函数级别实现授权的示例代码和示例。

基本上,如果请求未经授权,我会尝试阻止查询的执行。

谁能帮助我得到一些好的教程或代码样本作为实现的参考。

EN

回答 2

Stack Overflow用户

发布于 2018-11-30 15:41:45

对于graphql-dotnet/authorizationAspNetCore页面尚未发布,请参阅Add GraphQL.Server.Authorization.AspNetCore NuGet package #171

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

在实现Authorization.AspNetCore之后,您可以像这样配置Authorize

  • Startup.cs

公共类启动{公共启动( IConfiguration configuration,IHostingEnvironment hostingEnvironment) { Configuration = configuration;Environment = hostingEnvironment;}公共IConfiguration Configuration { get;}公共IHostingEnvironment环境{ get;} //运行时调用此方法。使用此方法将服务添加到容器中。public void ConfigureServices(IServiceCollection服务){ services.Configure(options => { //此lambda确定给定请求是否需要用户同意不必要的cookie。options= context => true;options.MinimumSameSitePolicy = SameSiteMode.None;});services.AddAuthentication(options => { option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;=> = CookieAuthenticationDefaults.AuthenticationScheme;option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);option.DefaultSignInScheme(options=>{ options.EnableMetrics = true;options.ExposeExceptions = Environment.IsDevelopment();//选项。}) .AddGraphQLAuthorization(options => { options.AddPolicy("Authorized",p => p.RequireAuthenticatedUser());//var AuthorizationPolicyBuilder= new AuthorizationPolicyBuilder() // .// options.AddPolicy(“=>”,p => p.RequireClaim(ClaimTypes.Name,"Tom"));});//.AddUserContextBuilder(context =>新用户{ GraphQLUserContext = context.User });services.AddSingleton();services.AddSingleton();options.AddPolicy}//运行时调用此方法。使用此方法可配置HTTP请求管道。public void Configure(IApplicationBuilder app,IHostingEnvironment环境){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage();} else { app.UseExceptionHandler("/Home/Error");app.UseHsts();} app.UseHttpsRedirection();app.UseStaticFiles();app.UseCookiePolicy();app.UseAuthentication();app.UseGraphQL( "/graphql“);app.UseGraphQLPlayground(新建路径(){GraphQLPlaygroundOptions= "/ui/playground”});app.UseGraphiQLServer(新建GraphiQLOptions { GraphiQLPath =“/ui/GraphQLPlaygroundOptions”,GraphQLEndPoint =“/graphql”});App.UseMvc(路由=> { routes.MapRoute(名称:"default",模板:"{controller=Home}/{action=Index}/{id?}");});}公共类MessageQuery : ObjectGraphType { }

  • Schemapublic MessageQuery() {ObjectGraphType(o => o.Content).Resolve(o => "This is Content").AuthorizeWith("Authorized");Field(o => o.SentAt);Field(o => o.Sub).Resolve(o => "This is Sub");} }

有关完整的演示,请参阅GraphQLNet

票数 10
EN

Stack Overflow用户

发布于 2020-01-24 02:30:28

要获得GraphQL.Net的授权才能在ASP.NET核心中工作,请首先安装此软件包:

代码语言:javascript
复制
GraphQL.Server.Authorization.AspNetCore

在Startup.cs中,在ConfigureServices中添加以下内容。确保添加以下using语句:

代码语言:javascript
复制
    using GraphQL.Validation;
    using GraphQL.Server.Authorization.AspNetCore;
代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
{
    //... other code

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services
        .AddTransient<IValidationRule, AuthorizationValidationRule>()
        .AddAuthorization(options =>
        {
            options.AddPolicy("LoggedIn", p => p.RequireAuthenticatedUser());
        });

    //... other code
}

现在,您将能够在解析器级别使用AuthorizeWith()来保护字段。示例:

代码语言:javascript
复制
public class MyQuery : ObjectGraphType
{
    public MyQuery(ProductRepository productRepository)
    {
        Field<ListGraphType<ProductType>>(
            "products",
            resolve: context => productRepository.GetAllAsync() 
        ).AuthorizeWith("LoggedIn");
    }
}

您还可以通过将this.AuthorizeWith()添加到查询构造函数的顶部来保护所有查询,如下所示:

代码语言:javascript
复制
 public class MyQuery : ObjectGraphType
 {
     public MyQuery(ProductRepository productRepository)
     {
         this.AuthorizeWith("LoggedIn");
         Field<ListGraphType<ProductType>>(
             "products",
             resolve: context => productRepository.GetAllAsync() 
         );
     }
 }

这样,对GraphQL端点的任何未经身份验证的访问都将被拒绝。

现在就登录而言,有很多方法可以做到这一点。下面是一个基于Cookie的快速身份验证示例:

在Startup.cs的ConfigureServices中配置基于cookie的身份验证:

代码语言:javascript
复制
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
        {
            o.Cookie.Name = "graph-auth";
        });

使用突变让某人登录:

代码语言:javascript
复制
public class Session
{
    public bool IsLoggedIn { get; set; }
}

public class SessionType : ObjectGraphType<Session>
{
    public SessionType()
    {
        Field(t => t.IsLoggedIn);
    }
}

public class MyMutation : ObjectGraphType
{
    public MyMutation(IHttpContextAccessor contextAccessor)
    {
        FieldAsync<SessionType>(
            "sessions",
            arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "password" }),
            resolve: async context =>
            {
                string password = context.GetArgument<string>("password");

                // NEVER DO THIS...for illustration purpose only! Use a proper credential management system instead. :-)
                if (password != "123")
                    return new Session { IsLoggedIn = false };

                var principal = new ClaimsPrincipal(new ClaimsIdentity("Cookie"));
                await contextAccessor.HttpContext.SignInAsync(principal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMonths(6),
                    IsPersistent = true
                });

                return new Session { IsLoggedIn = true };
            });
    }
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53537521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档