I'm trying to implement a custom authorization attribute with HotChocolate.
What I have so far is this
namespace GraphQL.Attributes
{
public class AuthorizeAttribute : ObjectFieldDescriptorAttribute
{
public override void OnConfigure(IDescriptorContext context, IObjectFieldDescriptor descriptor, MemberInfo member)
{
var httpContextAccessor = context.Services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
var authorizationHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString();
var jwtService = context.Services.GetService(typeof(JwtService)) as JwtService;
var isValidToken = jwtService.ValidateSessionToken(authorizationHeader);
if (isValidToken == false)
{
// Here I want to return an Unauthorized message to the client and abort any further execution
}
// Everything OK
return;
}
}
}
In ASP.NET 5 I can do it like this
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var httpContextAccessor = context.Services.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
var authorizationHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString();
var jwtService = context.Services.GetService(typeof(JwtService)) as JwtService;
var isValidToken = jwtService.ValidateSessionToken(authorizationHeader);
if (isValidToken == false)
{
context.Result = new UnauthorizedObjectResult(new
{
Code = 1,
Message = "Invalid token"
});
return;
}
// Everything OK
return;
}
}
As you can see, In ASP.NET we can set an UnauthorizedObjectResult
as the result and the API would return that.
How can I return an unauthorized result from my custom attribute in HotChocolate?
I guess I should use any of IDescriptorContext
, IObjectFieldDescriptor
or MemberInfo
.
Any suggestions?