Home > OS >  how to set AllowAnonymous for .NET Core graphql query
how to set AllowAnonymous for .NET Core graphql query

Time:12-29

I have graphql query in .NET Core 3.1 like these :

public class CommentQuery : ObjectGraphType
{
    public CommentQuery(CommentRepository commentRepository, UserInfo userInfo)
    {
        Field<ListGraphType<CommentType>>(
            "contentComments",
            arguments: new QueryArguments(new QueryArgument<StringGraphType> {Name = "contentItemId"}),
            resolve: x =>
            {
                var contentItemId = x.GetArgument<string>("contentItemId");
                
                return Task.Run(() =>
                    commentRepository.ListAsync(
                        Builders<Comment>.Filter.Where(p => p.ContentItemId == contentItemId))).Result;
            });
        
        Field<ListGraphType<CommentType>>(
            name: "Comments",
            arguments: new QueryArguments(new 
                QueryArgument<StringGraphType> { Name = "contentItemId" }),
            resolve: x =>
            {
                var commentId = x.GetArgument<string>("commentId");

                return Task.Run(() =>
                    commentRepository.ListAsync(
                        Builders<Comment>.Filter.Where(p => p.ContentItemId == commentId))).Result;
            }
        );
    }
}

I need to call this query without authentication. by default I enable authentication for all api in startup.cs

services.AddAuthentication(...)

CodePudding user response:

after search and trying i found solution : in Configure startup.cs method add some lines to allow specific path like this :

app.UseEndpoints(e =>
        {

            e.MapHealthChecks(BasePath   "/customers/comments/graphql", new HealthCheckOptions()
                {
                    Predicate = (_) => false
                })
                .WithMetadata(new AllowAnonymousAttribute());

        });

it work for me.

  • Related