如何在 GraphQL .Net Core 中进行授权?

问题描述

我正在尝试为使用 GraphQL 的应用程序 (.Net Core) 进行授权。但是我无法验证我可以通过突变登录并检查授权用户

启动文件

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient();

            services.AddCors();

            services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();

            services.Configure<CookiePolicyOptions>(options =>
            {
                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.AddScoped<IEventService,EventService>();

            services.AddScoped<AppSchema>();
            services.AddGraphQL(opt => opt.EnableMetrics = false)
                .AddSystemTextJson(deserializerSettings => { },serializerSettings => { })
                .AddErrorInfoProvider(opt => opt.ExposeExtensions = false)
                .AddGraphTypes(typeof(AppSchema),ServiceLifetime.Scoped)
                .AddGraphQLAuthorization(options =>
                {
                    options.AddPolicy("Authorized",p => p.RequireAuthenticatedUser());
                });

            services.AddControllers();

            services.AddResponseCompression();

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

我的变异文件

public class EventMutation : ObjectGraphType
    {
        public EventMutation(IEventService repository,IHttpContextAccessor contextAccessor)
        {
            Field<EventType>(
              "createEvent",arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<EventInputType>> { Name = "event" }
              ),resolve: context =>
              {
                  var eventData = context.GetArgument<EventModel>("event");
                  return repository.CreateEventAsync(eventData);
              });

            // AUTH MUTATION

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

                    // Only for test
                    if (password != "123")
                        return new Session { Authorized = false };

                    List<Claim> claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name,"Authorized")
                    };

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

                    return new Session { Authorized = true };
                });
        }
    }

但是如果我尝试执行受保护的查询,它会崩溃,我不应该被授权。

public class EventQuery : ObjectGraphType
    {
        public EventQuery(IEventService repository)
        {
            Field<ListGraphType<EventType>>(
               "events",resolve: context => repository.GetAllEventsAsync()
           );

            Field<ListGraphType<EventType>>(
               "eventsTest",resolve: context => repository.GetAllEventsAsync()
           ).AuthorizeWith("Authorized");
        }
    }

感谢您的回答

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)