HotChocolate with Authorize attribute, how to get currently logged on user?

Viewed 2363

I've got a GraphQL mutation using HotChocolate with the [Authorize] attribute from HotChocolate.AspNetCore.Authorization to enforce authorization on my GraphQL endpoints.

This works fine, I can only call the mutation once I'm logged in as an Admin ...

... but now I'd like to retrieve the user which is authorized, but I don't seem to find a way to do it.

[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;
    }
}

Any ideas?

1 Answers

HotChocolate uses the asp.net core authentication mechanisms, so you can get the user using the 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;
    }
}
Related