HotChocolate 带有 Authorize 属性,如何获取当前登录的用户?

问题描述

我使用 HotChocolate 和 [Authorize]HotChocolate.AspNetCore.Authorization 属性进行了 GraphQL 突变,以在我的 GraphQL 端点上强制执行授权。

这很好用,我只能在以管理员身份登录后调用突变...

...但现在我想检索已授权的用户,但我似乎没有找到方法。

[ExtendObjectType(Name = "Mutation")]
[Authorize(Roles = new[] { "Administrators" })]
public class MyMutations
{
    public bool SomeMethod()
    {
        // In a regular Web API controller,you can do User.Identity.Name to fetch the user name of the current user.  What is the equivalent in Hot Chocolate?
        var userName = "";


        return false;
    }
}

有什么想法吗?

解决方法

HotChocolate 使用 asp.net 核心身份验证机制,因此您可以使用 HttpContext 获取用户。

[ExtendObjectType(Name = "Mutation")]
[Authorize(Roles = new[] { "Administrators" })]
public class MyMutations
{
    public bool SomeMethod([Service] IHttpContextAccessor contextAccessor)
    {
        var user = contextAccessor.HttpContext.User; // <-> There is your user

        // In a regular Web API controller,you can do User.Identity.Name to fetch the user name of the current user.  What is the equivalent in Hot Chocolate?
        var userName = "";


        return false;
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...