authentication - 使用 JWT 使用 Asp.net 核心进行 GraphQL 身份验证

标签 authentication asp.net-core graphql graphql-dotnet

我用于 GraphQL for .NET graphql 的包。但我无法理解如何在 graphql 查询或变异中使用 JWT 进行身份验证。

我读了 guide about authorization但我无法完成。

我需要 GraphQL 方面的帮助以进行 .NET 身份验证。

任何帮助将不胜感激。

谢谢

最佳答案

该指南是关于授权的。您正在寻找的步骤是身份验证,并且由于可以使用 ASP.Net API Controller 实现 graphql,因此您可以像使用任何 Controller 一样实现 JWT 身份验证。

这是一个使用 Authorize 属性的示例 grapql Controller 。但是,您可以使用过滤器或如果您想要完全控制自定义中间件来实现此功能。

[Route("api/[controller]")]
[ApiController]
[Authorize]
public class GraphQLController : ControllerBase
{
    private readonly IDocumentExecuter executer;
    private readonly ISchema schema;

    public GraphQLController(IDocumentExecuter executer, ISchema schema)
    {
        this.executer = executer;
        this.schema = schema;
    }

    [HttpPost]
    public async Task<ActionResult<object>> PostAsync([FromBody]GraphQLQuery query)
    {
        var inputs = query.Variables.ToInputs();
        var queryToExecute = query.Query;

        var result = await executer.ExecuteAsync(o => {
            o.Schema = schema;
            o.Query = queryToExecute;
            o.OperationName = query.OperationName;
            o.Inputs = inputs;

            o.ComplexityConfiguration = new GraphQL.Validation.Complexity.ComplexityConfiguration { MaxDepth = 15};
            o.FieldMiddleware.Use<InstrumentFieldsMiddleware>();
        }).ConfigureAwait(false);

        return this.Ok(result);
    }
}

public class GraphQLQuery
{
    public string OperationName { get; set; }
    public string Query { get; set; }
    public Newtonsoft.Json.Linq.JObject Variables { get; set; }
}

在 Startup.cs 中,我配置了 JWT 不记名 token 身份验证。

希望这可以帮助。

关于authentication - 使用 JWT 使用 Asp.net 核心进行 GraphQL 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628455/

相关文章:

asp.net-core - 为什么 ASP.NET Core 将声明两次添加到 User.Claims 属性中?

c# - 如何使用包含点 (.) 的字符串路由参数在客户端 blazor 中进行路由?

reactjs - 无法使用 React-Query + Graphql-Request 在 useQuery 中传递参数

authentication - 我可以通过互联网使用kafka吗?

.net - 在 Windows 应用程序中保存用户凭据

django - 使用带有 token 而不是 Cookie 的 Django session 框架?

ruby-on-rails - 如何通过 :current_user in Graphql resolver

javascript - 推特弹出登录窗口

asp.net-core - 使用 itfoxtec-identity-saml2 时动态刷新用户声明

github - 使用 Github GraphQL 获取 secret 要点