我正在寻找有关如何使用GraphQL.NET和ASP.NET Core2在解析器函数级别实现授权的示例代码和示例。
基本上,如果请求未经授权,我会尝试阻止查询的执行。
谁能帮助我得到一些好的教程或代码样本作为实现的参考。
发布于 2018-11-30 15:41:45
对于graphql-dotnet/authorization,AspNetCore页面尚未发布,请参阅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 { }
有关完整的演示,请参阅GraphQLNet。
发布于 2020-01-24 02:30:28
要获得GraphQL.Net的授权才能在ASP.NET核心中工作,请首先安装此软件包:
GraphQL.Server.Authorization.AspNetCore在Startup.cs中,在ConfigureServices中添加以下内容。确保添加以下using语句:
using GraphQL.Validation;
using GraphQL.Server.Authorization.AspNetCore;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()来保护字段。示例:
public class MyQuery : ObjectGraphType
{
public MyQuery(ProductRepository productRepository)
{
Field<ListGraphType<ProductType>>(
"products",
resolve: context => productRepository.GetAllAsync()
).AuthorizeWith("LoggedIn");
}
}您还可以通过将this.AuthorizeWith()添加到查询构造函数的顶部来保护所有查询,如下所示:
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的身份验证:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o =>
{
o.Cookie.Name = "graph-auth";
});使用突变让某人登录:
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 };
});
}
}https://stackoverflow.com/questions/53537521
复制相似问题