所以我有 graphql 作为后端和 React / Apollo 作为前端。我已经实现了我的 JWT Token Auth,效果很好。
除此之外,我还有我的中间件,其中给出了 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);
}
}
}
}
直到这里它工作得非常好。
可悲的是,我正在努力挣扎。我添加了 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";
}
所以我想要的是:检查具有一个或多个角色的给定声明的字段级别(查询或突变)声明。