0

我正在尝试对使用 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");
        }
    }

感谢你的回答

4

0 回答 0