authentication - 使用 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");
}
}
解决方案
推荐阅读
- python - Python:得到一个带有意外网格线的输出图像
- php - 有什么办法可以在 html 中添加加载器,直到 PHP 代码正常工作?
- react-native - 使用 vscode 的 URL 更短的方式反应本机
- security - 我们可以通过其用户名了解关于远程机器人的哪些信息?
- angular - 如何在角度整合传单地图
- java - 在 java 中的现有 PDF 页面上添加 Barcode128
- c++ - 为什么引用成员不引用嵌套向量上的分配变量?什么是声明访问类成员的替代方法的正确方法?
- html - 表格列中的 HTML 文本不会居中对齐 (Spring)
- flutter - 如何使用带有 Flame/Flutter 的 PositionComponent 移动 Vector2?
- python - 如何添加列表中的最后两个元素并将总和添加到现有列表