Kov*_*ovu 2 c# graphql graphql-dotnet
所以我有 graphql 作为后端和 React / Apollo 作为前端。我已经实现了我的 JWT 令牌身份验证,效果很好。
除此之外,我还有我的中间件,其中提供了 HttpContext 并且用户正确加载了所有声明:
namespace xxx.Web.GQL.Middleware
{
public class GraphQLMiddleware
{
private readonly RequestDelegate _next;
private readonly IDocumentWriter _writer;
private readonly IDocumentExecuter _executor;
private readonly ISchema _schema;
public GraphQLMiddleware(RequestDelegate next, IDocumentWriter writer, IDocumentExecuter executor, ISchema schema)
{
_next = next;
_writer = writer;
_executor = executor;
_schema = schema;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.Request.Path.StartsWithSegments("/graphql") && string.Equals(httpContext.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
{
string body;
using (var streamReader = new StreamReader(httpContext.Request.Body))
{
body = await streamReader.ReadToEndAsync();
var request = JsonConvert.DeserializeObject<GraphQLQuery>(body);
var result = await _executor.ExecuteAsync(doc =>
{
doc.Schema = _schema;
doc.Query = request.Query;
doc.Inputs = request.Variables.ToInputs();
doc.ExposeExceptions = true;
doc.UserContext = httpContext.User;
}).ConfigureAwait(false);
var json = _writer.Write(result);
await httpContext.Response.WriteAsync(json);
}
}
else
{
await _next(httpContext);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
直到这里它工作得很好。
可悲的是,我正在进一步努力。我添加了 GraphQL.Authorization Nuget,但所有给定的信息都不足以让我用它构建一些工作代码。
我当然可以做的是在查询的解析器中访问 userContext 并“手动”检查它,但我尽量避免它;)
Field<StringGraphType>(
name: "hallo",
resolve: c =>
{
var userPrinc = (ClaimsPrincipal)c.UserContext;
var allowed = userPrinc.Claims.Any(x => x.Type == "Role" && x.Value == "Admin" || x.Value == "Mod");
if (!allowed)
{
throw new Exception("TODO: Make this a 401 FORBIDDEN");
}
return "World";
}
Run Code Online (Sandbox Code Playgroud)
所以我想要的是:检查具有一个或多个角色的给定声明的字段级声明(用于查询或突变)。
第一个需要定义策略。在ConfigureServices方法中执行此操作。例如:
services.AddGraphQLAuth(_ =>
{
_.AddPolicy("name-of-policy", p => p.RequireClaim("role", "admin"));
});
Run Code Online (Sandbox Code Playgroud)
并确保使用该AddUserContextBuilder方法添加用户上下文,例如:
services.AddGraphQL(options =>
{
options.ExposeExceptions = true;
}).AddUserContextBuilder(context => new GraphQLUserContext { User = context.User });
Run Code Online (Sandbox Code Playgroud)
最后,您需要使用作为字段AuthorizeWith一部分的扩展方法GraphQL.Authorization。例如:
Field<StringGraphType>( /* snip */ )
.AuthorizeWith("name-of-policy");
Run Code Online (Sandbox Code Playgroud)
看看这里的例子:https : //github.com/graphql-dotnet/authorization/tree/master/src/Harness
| 归档时间: |
|
| 查看次数: |
1009 次 |
| 最近记录: |