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

Hau*_*Haf 3 .net-core graphql hotchocolate

我使用 HotChocolate 进行了 GraphQL 突变,并使用[Authorize]from 属性HotChocolate.AspNetCore.Authorization在我的 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Fre*_*rke 6

HotChocolate 使用 asp.net core 身份验证机制,因此您可以使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我会被诅咒的。我认为*可能*是这种情况,但实际上我只是没有尝试。我真傻:)谢谢! (3认同)