Search code examples
asp.net-coregraphql.net-5hotchocolatecookie-httponly

How to modify Response Cookie in GraphQL using Hot Chocolate in .Net 5


I am building a GraphQL API using Hot Chocolate(.net 5) and need to add authentication using the JWT token.

In REST API, I have used http only cookie to add the refresh token.

var cookieOption = new CookieOptions
{
    HttpOnly = true,
    Expires = DateTime.UtcNow.AddDays(7)
};

Response.Cookies.Append("refreshToken", <refreshToken.Token>, cookieOption);

In my login mutation, I do not have access to HttpResponse as in REST API.

Even Hot Chocolate's documentation does not have an example or instruction on how to access the Http Response.


Solution

  • You can use the IHttpContextAccessor to access the HttpContext and in turn modify the cookies.

    public string Foo(string id, [Service] IHttpContextAccessor httpContextAccessor)
    {
        if (httpContextAccessor.HttpContext is not null)
        {
            httpContextAccessor.HttpContext.Response.Cookies...
        }
    }
    

    https://chillicream.com/docs/hotchocolate/fetching-data/resolvers/#ihttpcontextaccessor