首页 > 解决方案 > 使用 Auth0 在 Hot Chocolate 中进行授权和身份验证

问题描述

在用 REST 和控制器(所有工作)尝试了这个确切的东西之后,我想改用 GraphQL。ScopeHandler 似乎根本没有被调用(它在 REST 中调用了)。

我真的不知道我应该把我的 [Authorize] 注释放在哪里。在 REST 中,我将它放在 Controller 类或单个方法上。我想做类似的事情并以某种方式将其放入我的 QueryType 中。那可能吗?或者我应该怎么做?

这是我在启动中的代码:

var domain = Environment.GetEnvironmentVariable("AUTH0_DOMAIN");
services.AddAuthentication( JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = domain;
        options.Audience = Environment.GetEnvironmentVariable("AUTH0:AUDIENCE");
    });

services.AddHttpContextAccessor();

services.AddGraphQLServer()
    .AddQueryType<Query>()
    .AddAuthorization();

services.AddAuthorization(options =>
{
    options.AddPolicy("admin", policy => 
    {
        policy.Requirements.Add(new HasScopeRequirement("read:beer", domain));
    });
});

services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();

并在配置中。它看起来像这样:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseGraphQLPlayground(new GraphQLPlaygroundOptions
{
    Path = "/playground"
});

app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});

HasScopeHandler 看起来像这样:

public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
    {
            context.Succeed(requirement);
            return Task.CompletedTask;
    }
}

这是我在 GraphQl 中添加为类型的查询

public class Query
{
    [Authorize(Policy = "admin")]
    public Domain.Beer GetBeer()
    {
        return new Domain.Beer(Guid.NewGuid().ToString(), "Test", "Test", 5.0, "IPA");
    }
}

标签: authenticationgraphqlauth0.net-5hotchocolate

解决方案


推荐阅读